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.

    <ListView android:id="@+id/list_view"

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.)

<selector xmlns:android="">
    <item android:state_activated="true"
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.

<LinearLayout xmlns:android="">
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: