问题
I have a ListView with a TextView in each row. I have a default color.xml with is set in the row.xml
I have different colors for different states
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- pressed -->
<item
android:color="#ffffff"
android:state_pressed="true"/>
<!-- focused -->
<item android:state_selected="true"
android:color="#8b8989"/>
<!-- default -->
<item android:color="#ffffff"/>
</selector>
This works like a charm. But when Im trying to change the color for some rows in code, this doesn't seem to work. The second_color.xml looks just the same, but with different colors. The color is changed, but for the other states (not default) nothing changes.
I change the color like this:
TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(getContext().getResources().getColor(R.color.second_color));
回答1:
Solved it!
In order to set this in code it's required to create a ColorStateList.
ColorStateList cl = null;
try {
XmlResourceParser xrp = getResources().getXml(R.color.live_color);
cl = ColorStateList.createFromXml(getResources(), xrp);
} catch (Exception ex) {}
if(cl != null){
tl.setTextColor(cl);
}
回答2:
if your xml file is saved at /res/row.xml then you reference it with R.color.row
TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(R.color.row);
来源:https://stackoverflow.com/questions/7548653/settextcolor-of-textview-programmatically