Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a TextView's background color with a color defined in my values/colors.xml file?

I am working on an Android project using Eclipse. I want to change the background color of a TextView using one of the colors I've defined in res/values/colors.xml. These colors are all available by using R.color.color_name.

My problem is that this simply won't work. Changing to one of my defined colors always leaves the TextView's background set to its default color, in this case, black. If I use one of Java's built-in colors, it works fine. I'm thinking it's a color definition problem, something involving how 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>
like image 879
Phil Ringsmuth Avatar asked Feb 06 '11 04:02

Phil Ringsmuth


People also ask

How do I change text color in XML?

Android TextView – Text Color. TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.

What XML attribute should you use if you want to change text color?

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000" .

How do I add color to TextView?

There are two methods of changing the color of a TextView and the code for that has been given in both Java and Kotlin Programming Language for Android, so it can be done by directly adding a color attribute in the XML code or we can change it through the MainActivity File.


2 Answers

Actually it's even easier with this:

weight2.setBackgroundResource(R.color.darkgrey);
like image 87
Bostone Avatar answered Oct 05 '22 03:10

Bostone


It isn't working because you're setting the background color to the key itself (which is an hexadecimal value like 0x7f050008) instead of its value. To use it's value, try:

weight2.setBackgroundColor(getResources().getColor(R.color.darkgrey));
like image 43
goncalossilva Avatar answered Oct 05 '22 03:10

goncalossilva