Pages

Friday, June 20, 2014

Maintaining selection in ListView for multi-pane layouts

In this post, I will walk through setting up a list item that will remain In this post, I will walk through setting up a list item that will remain in a selected state after the user presses on an item. This is useful when you have a multi-pane layout and you want to show details for an item in a fragment next to the list view and keep the list item highlighted so your user doesn't loose context.

Below I'll lay out the steps to accomplish this goal with code snippets.

First, you'll need to set up your ListView's choiceMode by setting it to singleChoice.
[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 selector drawable and define another drawable for it's state_activated attribute. (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 background for 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.

No comments: