Defined color under res not usable in code
I defined a white color in mycolors.xml under res/values as below:
<开发者_如何学运维?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="my_white">#ffffffff</color>
</resources>
In my code, I set the text color of a TextView as the white color I defined:
TextView myText = (TextView) findViewById(R.id.my_text);
myText.setTextColor(R.color.my_white);
But the text in the TextView turned out to be a black color.
When I use @color/my_white in layout xml files, it works fine.
I check the generate R.java, and see:
public static final int my_white=0x7f070025;
Did I miss something?
Thanks.
R.color.my_white
is an ID that contains a reference to your resource. setTextColor
expects you pass a color, not a reference. The code compiles and gives no errors because setTextColor
expect an int
; but, of course, you are giving the wrong int
. In this case, you will have to convert the reference to a integer that represents that color:
Resources res = getResources();
int color = res.getColor(R.color.my_white);
myText.setTextColor(color);
Based on the Android developer docs, it looks like your reference should be:
myText.setTextColor(R.color.my_white);
ETA: As noted in Mayra's answer, R.id.my_white is probably returning a reference to the object that represents your colour rather than the ARGB value of the colour.
What you are providing setTextColor currently is the id of the my_white object, not the color my_white. I think what you want is R.color.my_white
.
精彩评论