I have a ListView, and it works great on a phone. Now I am making a tablet UI, with the ListView on the left and details on the right.
When I touch an item, it flashes blue as long as it is pressed. I want to keep that blue color until another item is selected, just like the Gmail app on the Nexus 7.
What is the cleanest way to achieve that? I'd rather avoid setting backgrounds manually, I assume there is a way to mark an element as the "active" one and theme it accordingly.
What is the cleanest way to achieve that?
What you are looking for is known as the "activated" state. To make this work:
Step #1: In res/values-v11/
, have a style resource that implements activated
. For example, for a new project that has the AppTheme
declaration defined there, go with something like:
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light"></style>
<style name="activated" parent="AppTheme">
<item name="android:background">?android:attr/activatedBackgroundIndicator</item>
</style>
</resources>
Step #2: Define the same style in res/values/
for any older devices, just as a stub style resource, so references to it continue to work:
<resources>
<style name="AppTheme" parent="android:Theme.Light"/>
<style name="activated" parent="AppTheme"/>
</resources>
Step #3: In your layout XML resource for the row in the ListView
, add style="@style/activated"
to the list of attributes of the root element
Step #4: Set the ListView
to be a single-choice list, such as the following line in a ListFragment
:
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
You can see this in action in this sample project, this sample project, and this sample project. For more background on those first two samples, see this SO question: Complete Working Sample of the Gmail Three-Fragment Animation Scenario?