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?