The Android ListView selector changes the background image and text color at the same time

advertisements

This is my selector xml.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:drawable="@drawable/listview_bg" />
<item android:state_focused="true" android:drawable="@drawable/listview" />
 <item android:state_window_focused="false" android:drawable="@drawable/listview_bg" />
</selector>

I want to change the background image and the color of the text at the same time, how can I modify the xml code?

I have tried to add android:color="#FFFFFF" at each item lines, but it is not working.


What you show us is a drawable selector. So it will select the drawable following the state of the view (pressed, focused, ...).

You need to use the same pattern but for a color. Create a directory color in your res directory and inside that color directoy a file selectable_color.xml

In this file, put the following :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#FF0000" />
    <item android:color="#00FF00" />
</selector>

So the selectable_color will be red when pressed and blue otherwise. Now in your textviews or buttons, use this color as usual android:textColor:@color/selectable_color. Now when the user will press view, its text color will change from blue to red.

However, if pressed is the not the state you looking for, don't hesitate to chnage it, it's the same thing as for the drawable.