tags:

views:

65

answers:

3

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.

A: 

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.

Mayra
There is a typo in my question. Actually, my code is writing: myText.setTextColor(R.color.my_white);
+1  A: 

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.

eldarerathis
There is a typo in my question. Actually, my code is writing: myText.setTextColor(R.color.my_white);
Have you tried following the later part of the doc where it gives an example of retrieving the colour resource?
eldarerathis
I got it. The correct way to write the code should be: myText.setTextColor(getResources().getColor(R.color.ff_white)); Thanks!
+4  A: 

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);
Cristian