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>
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.
In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000" .
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.
Actually it's even easier with this:
weight2.setBackgroundResource(R.color.darkgrey);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With