How to set TextColor using setTextColor(ColorsStateList colors)

非 Y 不嫁゛ 提交于 2019-12-20 08:37:14

问题


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

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

edit, solved:

textView.setTextColor(new ColorStateList(
   new int [] [] {
      new int [] {android.R.attr.state_pressed},
      new int [] {android.R.attr.state_focused},
      new int [] {}
   },
   new int [] {
      Color.rgb (255, 128, 192),
      Color.rgb (100, 200, 192),
      Color.White
   }
));

solution 2

textView.setTextColor(getResources().getColorStateList(R.color.your_colors))

Change Background Color of TextView on Click


回答1:


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>



回答2:


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




回答3:


you can also use ContextCompat to load a color state list

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


来源:https://stackoverflow.com/questions/6678694/how-to-set-textcolor-using-settextcolorcolorsstatelist-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!