basically, I have a ListView in my android application. I want it to be possible for the user to select multiple rows by clicking on them. To implement this, I’ve made a class that implements onItemClickListener, and the ListView sets this as the OnItemClick Listener.
This is the code in the listener:
public void onItemClick(AdapterView<?> parentAdapterView, View viewSelected, int pos, long id) {
if(selectedItems.contains(viewSelected)) {
//remove it from the selected list.
selectedItems.remove(viewSelected);
viewSelected.setBackgroundColor(Color.BLACK);
}
else {
selectedItems.add(viewSelected);
viewSelected.setBackgroundColor(Color.RED);
}
}
The selectedItems is simply a List of Views (List), that I used to keep track of all the items that have been selected.
This works fine until the number of items causes the list to overflow (and thus, the list becomes scrollable). Then, when one item is clicked, another item is highlighted (in addition to the first) further down the list?
Can’t think why this would be happening? I’ve searched around on Google, but to no avail…
I’d be grateful for any help on the matter.
Cheers
Edit: The code that I used to provide the views for list view is simply:
uiListViewRes = R.layout.main_list_item;
ListView overTwoDaysView = (ListView) findViewById(R.id.overtwolistview);
String[] from = {"_id","foodItemName", "expire", "dateAdded"};
int[] to = {R.id.itemIDhidden,R.id.name, R.id.expiry, R.id.dateAddedLabel};
SimpleAdapter overTwoDaysAdapter = new SimpleAdapter(this, adapter.getAllItemsOverTwoDays(), uiListViewRes, from, to);
overTwoDaysView.setAdapter(overTwoDaysAdapter);
The problem is that ListView reuses Views for better performance.
So ListView allocates only X number of Views and then tries to reuse the not visible ones – by changing the properties of the View.
That means that you can’t save the Views/set the background of the Views because that same View instance will be used later in the ListView.
There are several approaches to solve this problem:
You can have a look at the ListView’s CHOICE_MODE_MULTIPLE
Example: http://www.vogella.de/articles/AndroidListView/article.html
You can save the ID or position of the row and use it in a custom Adapter to set the background accordingly.