How to define ColorStateList for TextView?

Viewed 44217

When my ListViewItem is highlighted, I want the text to turn white. How can I define this?

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:color="@color/testcolor1"/>
   <item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
   <item android:state_enabled="false" android:color="@color/testcolor3" />
   <item android:color="@color/testcolor5"/>
 </selector>
3 Answers

Try this...

First, create a color state list text_color.xml placed in res/color directory.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="MissingDefaultResource">
  <item android:color="#000000" android:state_enabled="false"/>
  <item android:color="#FFFFFF"/>
</selector>

Second, use

getColorStateList(@NonNull Context context,
            @ColorRes int id)

method to get color state list.

textView.setTextColor(ContextCompat.getColorStateList(context, R.color.text_color))

Third, enable(true) or disable(false) based on your requirements,

textView.isEnabled = true //when item is highlighted
Related