49

I need to change text color when state change(pressed, focus)...

How to set the text color of a TextView using ColorsStateList?

3

3 Answers 3

79

If you need to set the colors in code (using ColorStateList), but still want to keep the color states in an XML, you might want to use this:

try {
    XmlResourceParser parser = getResources().getXml(R.color.your_colors);
    ColorStateList colors = ColorStateList.createFromXml(getResources(), parser);
    mText.setTextColor(colors);
} catch (Exception e) {
    // handle exceptions
}

res/color/your_colors.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#222222"/>
    <item android:state_selected="true"
          android:color="#222222"/>
    <item android:state_focused="true"
          android:color="#222222"/>
    <item android:color="#0000ff"/>
</selector>
5
  • 105
    There is a much simpler way to achieve this: mText.setTextColor(getResources().getColorStateList(R.color.your_colors));
    – ol_v_er
    Commented May 25, 2012 at 13:53
  • @ol_v_er it doesn't seem to retain the color states if you set it that way (at least it wasn't for me). I had to use the method above in order to retain the selected color state, etc.
    – Pete Lada
    Commented Dec 11, 2012 at 0:58
  • When does it doesn't retain the color states? When an configuration change occurs?
    – ol_v_er
    Commented Dec 11, 2012 at 15:22
  • 2
    Ol_v_er's method (in the first comment, not in the answer) worked perfectly for me, all the states are retained (Android 2.3 & 4.4).
    – javaxian
    Commented Apr 29, 2014 at 10:17
  • Just to update this for 2017, the better way would now be: mText.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.my_color_statelist);
    – Chris
    Commented Feb 16, 2017 at 17:23
28

You have to use getColorStateList()

I was also struggling with this problem, if you want to use a state list, you need to declared it in the color resources folder, instead of the drawable folder, and use the setTextColor(getResources().getColorStateList(R.color.your_colors)).

1
  • This was the solution for me. Android Studio 2.3 was showing very inconsistent behaviour with the selector in the 'drawable' folder. Sometimes it would work, sometimes it would get confused and just colour all the text pink. By adding a 'color' resource folder and putting the selector XML file in there, everything came good.
    – Neil B
    Commented Mar 23, 2017 at 11:07
6

You can also use ContextCompat to load a color state list

ColorStateList colors = ContextCompat.getColorStateList(this,R.color.my_color_list);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.