简体   繁体   中英

Change background color of list item in listview when it is selected

How can i Change background color of list item in listview when it is selected.

In res/drawable folder i have create listselector.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/focused"/> 

  <!-- Pressed -->
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/selected" /> 
</selector>

then in values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <drawable name="focused">#ff5500</drawable>
    <drawable name="selected">#FF00FF</drawable>

</resources>

This is listview.xml

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
           android:layout_below="@+id/textView6"
        android:layout_height="75dp"
          android:textColor="#FFFFFF"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="33dp"
         >
    </ListView>

</LinearLayout>

but it is not changing the background color of list item when selected...

There's no link between your ListView and it's selector. You need to add the following line of code to your listview.xml .

android:listSelector=“@drawable/listselector"

I hope this helps.

Look here . Althought its older, there is implementiation of custom color on items click. I think it has to do something with android:drawable. Try to use

android:color="@color/yourcolor"

And put your drawables to colors:

<color name="focused">#ff5500</color>
<color name="selected">#FF00FF</color>

Its in /res/values/colors folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM