AndreaF
AndreaF

Reputation: 12375

How to Customize ListView Seletion in Android

I want to customize the selection effect of the items in the listView, but I don't know the way.

Will be useful if I should change the selection item background with a different png when the user select the item.

Any suggestion?

Upvotes: 0

Views: 61

Answers (2)

Lazy Ninja
Lazy Ninja

Reputation: 22527

Use a selector for this:

<ListView android:id="@+id/list" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" 
      android:layout_gravity="center"
      android:divider="@null" 
      android:dividerHeight="0dip"
      android:listSelector="@drawable/list_selector" />

the selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" 
        android:state_pressed="false"
        android:drawable="@drawable/yourdrawable" />
    <item android:state_focused="true" 
        android:state_pressed="true"
        android:drawable="@drawable/yourdrawable" />
    <item android:state_focused="false" 
        android:state_pressed="true"
        android:drawable="@drawable/yourdrawable" />
    <item android:drawable="@drawable/yourdrawable" />
</selector> 

Here is a good tutorial for it.

Upvotes: 1

Abhishek Nandi
Abhishek Nandi

Reputation: 4275

What you are looking for is selector Create a selector xml in res and set the background for the list item to the selector xml. Example:

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/selected" /> <item android:drawable="@drawable/normal" /> </selector>

Also look at: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

Upvotes: 1

Related Questions