Multiple selection List View

ListView is also a kind of AdapterView, and is very alike ExpandableListView, which has been introduced in last post. To custome a ListView, we need to provide a layout file for elements in the listView, and a adapter class to provide data for ListView. In the demo project, I wrote a multiple selection ListView, I used my own logic to enable multiple selection, which is different from methods using checkbox. The screenshot of the demo is like below.multiple selection listView

Each row there are three views, one ImageView used as indicator to indicate whether an element is selected or not, one ImageView for country flag and a textView to display country name. The definition of the layout is not complicated, you can refer the code for detail.

When we subclass ArrayAdapter class, we need to override two method, public int getCount() which returns the number of elements in the ListView and public View getView which populate view for each element. In order to enable multiple selection, we need to manage the selected items by ourselves, we can use an ArrayList to achieve this easily, only with methods below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//check if pos is selected
public int isSelected(int pos)
{

for(int i = 0; i < this.selections.size(); ++i)
{
if (this.selections.get(i).intValue() == pos)
return i;
}
return -1;
}

//when user clicks an element in ListView, we need to update selecion info
public void updateSelection(int pos)
{

int index = this.isSelected(pos);
if(index == -1)
{
this.selections.add(pos);
}
else
{
this.selections.remove(index);
}
}

//return all selected items, just for toast to display.
public String getAllSelectedItem()
{

String result = " ";
for(int i = 0; i < this.selections.size(); ++i)
result += this.model.get(this.selections.get(i).intValue()).country + " ";

return result;
}

In our OnItemClickListener of ListView, we have to update the selection, and let listView redraw itself to chagne the state of the indicator drawable.

1
2
3
listAdapter.updateSelection(arg2);//update selection
listAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, listAdapter.getAllSelectedItem(), 1).show();