2015-11-19 94 views
1

我正在尝试创建一个ListView,您可以一次点击不超过4个项目。 这些项目必须彼此相邻。ListView - 获取点击项目的相邻项目

当我点击我的第一个项目,我想看看是否先前或以下项目已被点击。

注:当我单击一个项目时,我更改背景颜色。所以如果我想告诉一个项目是否被点击,我只想检查背景颜色。

public void OnItemClick(AdapterView<?> parent, View, view, int position, long id){ 

    View currentItem = view; 
    currentItem.setBackgroundResource(R.drawable.li_gradient); 

    // How do I get the view in front of and behind currentItem 
    // to check their current background color? (Assuming they exist) 

} 

回答

0

您应该在您的适配器类中执行此操作,模型项需要具有后台资源属性。

只投适配器,拿到上一个或下一个项目,设置新的背景和通知的ListView

public void OnItemClick(AdapterView<?> parent, View, view, int position, long id){ 

    YourAdapterClass adapter = (YourAdapterClass) parent.getAdapter(); 

    // TODO check if is a valid position 
    YourItem item = (YourItem) adapter.getItem(position-1); 
    item.setBackgroundResource(R.drawable.li_gradient); 

    adapter.notifyDataSetChanged(); 
} 
0

请记住,如果活动被重建(例如因为配置更改的),或者如果列表视图会重新绘制(例如,当它收到更改通知时),它不会自动了解onClick方法中对视图所做的更改,并且背景更改可能会丢失。我会用itemSelected(int i),clearAllSelected(),getSelectedItems()等方法制作一个自定义AdapterView,并使adapterview成为跟踪和维护这些更改以及渲染背景的单一责任点。

卡梅尔