Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change color of selected listview item

I want to change color of list item when it will press

For that I did like below,

list_item_selector.xml

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

    Selected 
  <item 
    android:state_focused="true" 
    android:state_selected="false" 
    android:drawable="@drawable/list_focused"/> 

  Pressed
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/list_selected" />  

</selector> 

I have set the color in colors.xml like below,

 <drawable name="list_focused">#36C170</drawable>
  <drawable name="list_selected">#9EC136</drawable>

and in my ListView I wrote like this,

<ListView
            android:id="@+id/list_centers_complete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:cacheColorHint="@android:color/transparent"
            android:listSelector="@drawable/list_item_selector" />

but when I am clicking on list item, the whole background color is changed instead of only list item.

How can I solve this? Is there any way?

Thank you

like image 589
Jyosna Avatar asked Dec 09 '11 08:12

Jyosna


1 Answers

Apply "@drawable/list_item_selector" to the row of that list(List item) not a List itself..

Something like, your list item (list row)..

<?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="fill_parent"
    android:orientation="horizontal"
    android:background="@drawable/list_item_selector">
        <TextView       android:id="@+id/textForList"
        android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:padding="10sp"  />
.
.
.
</LinearLayout>

list_item_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
    <shape>
        <solid android:color="#66FFFFFF" />
    </shape>
</item>
    <item>
    <shape>
        <solid android:color="#FF666666" />
    </shape>
</item>

</selector>
like image 119
user370305 Avatar answered Oct 16 '22 02:10

user370305