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.
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 | //check if pos is selected |
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 | listAdapter.updateSelection(arg2);//update selection |