Wow, documentation is horrible when it comes to list item selection. All I need is to be able to select and highlight multiple items in a list. I've scoured the web and seen references to android:choiceMode="multipleChoice"
, which I'm guessing allows you to select multiple items. But where can I get the selected items in my Activity? And how come when I try to select multiple items using setSelection(position)
, the previously highlighted item disappears?
Google also describes in View.setActivated(boolean)
that
Note that activation is not the same as selection. Selection is a transient property, representing the view (hierarchy) the user is currently interacting with. Activation is a longer-term state that the user can move views in and out of. For example, in a list view with single or multiple selection enabled, the views in the current selection set are activated. (Um, yeah, we are deeply sorry about the terminology here.)
So am I supposed to use activation instead of selection? This SO answer talks about how "activated" is just the post-HoneyComb version of "checked". But if you're supposed to use "activated" for multiple selection, whats the point of android:choiceMode="multipleChoice"
in the first place?
So apparently I was led off the wrong track because I was supposed to be looking for highlighting "checked" items and not "selected" items. Thus, many answers told me to use the selector
with my ListView layout using android:listSelector="@drawable/myselector
, but what I really needed was to use the selector
with my row layout. The solution is actually rather simple, I'll post it below:
drawable/rowbackgroundselector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:drawable="@android:color/holo_green_light"/>
</selector>
drawable/mylistrow.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:background="@drawable/rowbackgroundselector"
android:padding="10sp"
/>
MainActivity.onListItemClick()
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(pos, true);
}
Lastly, make sure your adapter is using your custom row layout
mAdapter = new ArrayAdapter<FileTag>(this.getActivity(),
R.layout.mylistrow, mList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With