How to set TextColor using setTextColor(ColorsStateList colors)

前端 未结 3 1060
北恋
北恋 2021-01-30 08:56

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

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

相关标签:
3条回答
  • 2021-01-30 09:17

    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>
    
    0 讨论(0)
  • 2021-01-30 09:18

    you can also use ContextCompat to load a color state list

    ColorStateList colors = ContextCompat.getColorStateList(this,R.color.my_color_list);
    0 讨论(0)
  • 2021-01-30 09:25

    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)).

    0 讨论(0)
提交回复
热议问题