Android 如何使用setTextColor(ColorsStateList颜色)设置TextColor
我需要在状态更改时更改文本颜色(按下,焦点) 如何使用Android 如何使用setTextColor(ColorsStateList颜色)设置TextColor,android,textcolor,Android,Textcolor,我需要在状态更改时更改文本颜色(按下,焦点) 如何使用颜色StateList设置文本视图的文本颜色 编辑,已解决: textView.setTextColor(new ColorStateList( new int [] [] { new int [] {android.R.attr.state_pressed}, new int [] {android.R.attr.state_focused}, new int [] {} }, new
颜色StateList
设置文本视图的文本颜色
编辑,已解决:
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
}
));
解决方案2
textView.setTextColor(getResources().getColorStateList(R.color.your_colors))
如果需要在代码中设置颜色(使用ColorStateList),但仍希望在XML中保留颜色状态,则可能需要使用以下方法:
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>
您必须使用
我也在努力解决这个问题,如果你想使用状态列表
,你需要在color
resources文件夹中声明它,而不是drawable
文件夹,并使用setTextColor(getResources().getColorStateList(R.color.your\u colors))
您还可以使用ContextCompat加载颜色状态列表
ColorStateList colors = ContextCompat.getColorStateList(this,R.color.my_color_list);
你读过这个吗?你的问题模棱两可-你只是想找一个关于ColorStateList使用的教程吗?你到处找过了吗?是的,但是我不能使用XML。我需要通过编程来实现这一点有一种更简单的方法:mText.setTextColor(getResources().getColorStateList(R.color.your_colors))
@ol\u v\u er如果你这样设置,它似乎不会保留颜色状态(至少对我来说不是这样)。我必须使用上面的方法来保留所选的颜色状态,等等。它什么时候不保留颜色状态?当配置发生变化时?Ol_v_er的方法(在第一条评论中,而不是在答案中)对我来说非常有效,所有的状态都被保留(Android 2.3和4.4)。为了在2017年更新它,现在更好的方法是:mText.setTextColor(ContextCompat.getColorStateList(getContext(),R.color.my_color_statelist);这是我的解决方案。Android Studio 2.3与“drawable”文件夹中的选择器表现出非常不一致的行为。有时会起作用,有时会混淆,只是将所有文本涂成粉红色。通过添加“color”资源文件夹并将选择器XML文件放在其中,一切都很好。