How to define ColorStateList for TextView?

43,293

Solution 1

Create file res/drawable/text_color.xml:

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" />
    <item android:state_focused="true" android:state_pressed="true" android:color="#ffffff" />
    <item android:state_focused="false" android:state_pressed="true" android:color="#ffffff" />
    <item android:color="#000000" />
</selector>

Then use @drawable/text_color from xml (or R.drawable.text_color from code) as text color for your list view items.

Solution 2

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

Solution 3

In addition to what others have stated above, I would like to highlight one point, taken from the below url.

https://developer.android.com/reference/android/content/res/ColorStateList.html

Note: The list of state specs will be matched against in the order that they appear in the XML file. For this reason, more-specific items should be placed earlier in the file. An item with no state spec is considered to match any set of states and is generally useful as a final item to be used as a default.

It's important that you have the broader condition towards the bottom in the selector tag.

Share:
43,293
Sheehan Alam
Author by

Sheehan Alam

iOS, Android and Mac Developer. i can divide by zero.

Updated on October 30, 2021

Comments

  • Sheehan Alam
    Sheehan Alam over 2 years

    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>