Pages

mardi 28 mai 2013

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

0 commentaires:

Enregistrer un commentaire