0

I am using this code below, but it doesn't work properly: If I select an item, the background is changed. But the background change also if I put only focus on the item without selecting it. Why ?

Added to my listview:

android:listSelector="@drawable/bg_key"

@drawable/bg_key

<?xml version="1.0" encoding="utf-8"?>
<selector
    android:id="@+id/myselector"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_activated="false"
        android:drawable="@color/activated_color" />

</selector>

color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="activated_color">#1d1d1d</color>
</resources>
xRobot
  • 25,579
  • 69
  • 184
  • 304

2 Answers2

0

You can highlight/provide ripple effect to your list items using the following :

Create a selector item_ripple.xml in your drawable :

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

    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/activated_color"></solid>
        </shape>
    </item>

    <item >
        <shape>
            <solid android:color="@android:color/transparent"></solid>
        </shape>
    </item>

</selector>

Create a selector item_ripple.xml in your drawable-v21

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

    <item
        android:id="@android:id/mask"
        android:drawable="@android:color/white" />
</ripple>

You need to add these selector as background of your item layout :

android:background="@drawable/item_ripple"
nipun.birla
  • 719
  • 5
  • 19
  • what is drawable-v21 ? – xRobot Jan 30 '17 at 13:09
  • Create a new directory in your res folder and name it as drawable-v21. This signifies if the current API version of OS is <=21, consider using the resources present in this folder, if not present, resources under drawable folder are used by default. – nipun.birla Jan 30 '17 at 13:32
0

You can use pressed state in your selector file

/drawable/list_selector.xml

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

<item android:drawable="@android:color/holo_red_light" android:state_pressed="true"/>

</selector>

then set following attribute in your listView

android:listSelector="@drawable/list_selector"
Majeed Khan
  • 505
  • 7
  • 16