Below I'll lay out the steps to accomplish this goal with code snippets.
First, you'll need to set up your
choiceModeby setting it to
[layout/fragment_list_and_detail.xml] ... <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" android:choiceMode="singleChoice"/> ...
At this point, your list item will have an activated state when the user presses it. But, we haven't set up what it should look like when in this state. For this example, it will change background color to set it apart from the rest of the list items.
To do that, we'll create a
selectordrawable and define another
state_activatedattribute. (Here we are just using a color resource, but it could be any type of drawable.)
[drawable/selector_list_view_item.xml] <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true" android:drawable="@color/highlight_blue"/> </selector>Now that we've defined a selector to handle the activiated state, we just need to set the selector as the
backgroundfor the root layout that defines this list item.
[layout/list_view_item.xml] <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/selector_list_view_item"> ... </LinearLayout>And that's it! Now you have a ListView where the selected item will maintain it's selected state for use in multi-pane layouts.