Android ListView : highlight selected item

In this android tutorial, i will show you how to highlight the selected item of a ListView, so that it keeps being highlighted. By default, the highlight disppears so in a list-detail page, you don’t see which item has been selected. Other people use a radio to do that, but i prefer to change the background color to lighten the UI. Let’s see a little demo:

If you wish to test before, you can install the application with the following link :

logo-app
Your app idea
Michenux
Free   
pulsante-google-play-store
pulsante-appbrain
qrcode-app

Let’s start tutorial:

First thing is to configure the ListView to singleChoice because only one item can be selected :

<ListView
       android:id="@android:id/list"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:choiceMode="singleChoice">
</ListView>

Then, you need to create a selector. This is where you will configure colors for each defined state. The selected file
is in res/drawable directory.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_mediumAnimTime">

   <item android:drawable="@android:color/holo_orange_dark" android:state_pressed="true"/>
   <item android:drawable="@android:color/holo_green_light" android:state_selected="true"/>
   <item android:drawable="@android:color/holo_green_light" android:state_activated="true"/>

</selector>

Then, on the item layout, add the attribute activatedBackgroundIndicator at top level:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:background="?android:attr/activatedBackgroundIndicator">
   
    <!-- your item content-->
</LinearLayout>

Finally, you need to link the selector with your ListView. This can be done in method onCreate of a ListActivity or
in method onActivityCreated of a ListFragment.

this.getListView().setSelector(R.drawable.your_selector);

That’s all.

Update (2013/05/30) :

I didnot explain how to change the blue color.
Here is the solution :

Create a file res/drawable/listitem_background.xml with the following content :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@color/purple_dark" />
    <item android:drawable="@android:color/transparent" />
</selector>

Replace the @color/purple_dark with the color of your choice.

Then, in your theme, add the following line :

<item name="android:activatedBackgroundIndicator">@drawable/listitem_background</item>
Share Button

Comments

Leave a Reply