我的代码:
ArrayList<Integer> selectedItemIds = new ArrayList<>();
boolean isItemSelected = false;
main_listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Object object = parent.getItemAtPosition(position);
if(object instanceof Listview_Item_Details)
{
TextView itemName = (TextView) view.findViewById(R.id.listview_itemName);
TextView itemDetails = (TextView) findViewById(R.id.listview_itemDetails);
if(!selectedItemIds.isEmpty())
{
for(int i = 0; i < selectedItemIds.size();i++)
{
if(selectedItemIds.get(i) == position)
{
isItemSelected = true;
if(selectedItemIds.size() == 1)
{
selectedItemIds.clear();
}
else
{
selectedItemIds.remove(i);
}
}
}
if(isItemSelected)
{
view.findViewById(R.id.custom_listview_item).setBackgroundResource(R.drawable.listview_item_background);
itemName.setTextColor(getResources().getColor(R.color.colorBlack));
itemDetails.setTextColor(getResources().getColor(R.color.colorGray_Dark));
isItemSelected = false;
}
else
{
selectedItemIds.add(position);
view.findViewById(R.id.custom_listview_item).setBackgroundResource(R.drawable.listview_selected_item_background);
itemName.setTextColor(getResources().getColor(R.color.colorWhite));
itemDetails.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
else
{
selectedItemIds.add(position);
view.findViewById(R.id.custom_listview_item).setBackgroundResource(R.drawable.listview_selected_item_background);
itemName.setTextColor(getResources().getColor(R.color.colorWhite));
itemDetails.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
return true;
}
});
注意:“ custom_listview_item”是项目的自定义布局的RelativeLayout,两个文本视图都在其中。
现在一切正常,但就像我说的那样,如果我不滚动列表视图并选择/取消选择多个项目,它可以工作,但我滚动它会随机更改多个项目的背景,甚至更改所选项目的背景。
这是什么问题?
答案 0 :(得分:0)
使用Recyclerview
代替Listview
来处理这种情况并自定义视图项。