Select multiple items from listview and change color of selected item only
The issue here is that you are setting the background color to the view, then when you scroll, you end up reusing that view due to using convertView
. This is exactly what you should be doing, so good job there.
But, of course, that means list items are selected when they shouldn't be. In order to fix this, your getView()
method needs to reset the background color to its default value. I don't know what the color was originally, but I'll assume it was transparent. So you would put:
textView.setBackgroundColor(android.R.color.transparent);
So now you're setting the background color to its default, but if you scroll away from the selected item, then back to it, it will have a transparent background instead of the selected background. To resolve this, put an ArrayList
of Integer
values inside your adapter class. When an item is clicked and onItemClick()
is triggered, add the item position to that ArrayList
. For example, say you have:
public ArrayList<Integer> selectedIds = new ArrayList<Integer>();
in your adapter class. Then, your onItemClick
method would look like this:
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ArrayList<Integer> selectedIds = ((ItemsAdapter) parent).selectedIds;
Integer pos = new Integer(position);
if(selectedIds.contains(pos) {
selectedIds.remove(pos);
}
else {
selectedIds.add(pos);
}
parent.notifyDataChanged();
}
So, finally, in your getView()
method, add this line:
textView.setBackground(selectedIds.contains(position) ? R.color.result_image_border : androi.R.color.transparent);
I have also encountered this problem, and found out that it is because recycling views. If i remember right setting this removes recycling and fixes the problem, but it's not the best option here.
@Override
public int getItemViewType(int position) {
return IGNORE_ITEM_VIEW_TYPE;
}