sosergio sosergio - 1 month ago 7
Android Question

Android ListView CHOICE_MODE_MULTIPLE, how to set checked index?

I'm using the cool feature of the ListView to show a checkbox next to the item in the ListView.
I bind my list to an array of strings.
The onClick and onSelectedItem listeners get called fine, in this way I know the index of the "string" checked (or unchecked).

I'm storing all the checked strings into preferences (as a comma-concatenated-string), and everytime the activity becomes visible I would like to set the checked items back in the listview.

Is there a way of doing it? or the CHOICE_MODE_MULTIPLE doesn't allow to set the checked items?

note: I'm not using a custom view, since what I want to display is just a string and a checkbox. I've tried setSelection(index) but it should set the onlyone selected (highlighted) row.

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,names);
m_playlists_list.setAdapter(adapter);
m_playlists_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

Answer

Use the setItemChecked method of ListView

Sets the checked state of the specified position. The result is only valid if the choice mode has been set to CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.