Setting TextView color to a <selector> programmatically
I have the following selector defined in an XML file under res/color/redeemlist_item_color.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="#FFFFFF" /> <!-- pressed -->
<item android:state_selected="开发者_StackOverflowtrue"
android:color="#FFFFFF" /> <!-- focused -->
<item android:color="#000000" /> <!-- default -->
</selector>
I also have a TextView
in a ListView
item layout. When I set android:textColor
on this TextView
to the above selector in XML, then the color changes correctly when the item is selected. However, I am trying to set this resource programmatically in the following way:
holder.label.setTextColor(R.color.redeemlist_item_color);
When set in this way, the color no longer changes. Can a selector be assigned to a TextView
in this way?
I think you might need to add findViewById
or something of that variety
Edit: the above is incorrect as per my comment the proper answer is
setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color));
You have to use getColorStateList()
I was also struggling with this problem, if you want to have use a state list
, you need to declare it in the color
resources folder, instead of the drawable
folder, and use the setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color))
.
You can try:
holder.label.setTextColor(getResources().getColor(R.color.redeemlist_item_color));
instead of :
holder.label.setTextColor(R.color.redeemlist_item_color);
Rasman is correct. You need to give the TextView an ID, android:id="@+/something". You retrieve a reference to that particular using that ID and findViewById, and then you may set the text color.
精彩评论