How do I change the background color of a TextView with the color specified in my values ​​/colors.xml files?

I am working on an Android project using Eclipse. I want to change the background color of a TextView using one of the colors that I defined in res / values ​​/colors.xml. All of these colors are available using R.color.color_name.

My problem is that it just won't work. Switching to one of my defined colors always leaves the TextView's background color equal to its default color, in this case black. If I use one of the built-in Java colors, it works fine. I think this is a color definition problem, which is related to the way I actually define my colors in my XML, but I'm not sure.

// This works: weight1.setBackgroundColor(Color.BLACK); // This does not work: weight2.setBackgroundColor(R.color.darkgrey); // Color Definition: (this is in a separate xml file, not in my Java code) <color name = "darkgrey">#A9A9A9</color> 
+6
android textview
source share
2 answers

It does not work because you set the background color of the key itself (which is a hexadecimal value, for example 0x7f050008 ), and not its value. To use this value, try:

 weight2.setBackgroundColor(getResources().getColor(R.color.darkgrey)); 
+11
source share

This is actually even simpler:

 weight2.setBackgroundResource(R.color.darkgrey); 
+20
source share

All Articles