如何使用在values/colors.xml文件中定义的颜色更改TextView的背景颜色? [英] How to change a TextView's background color with a color defined in my values/colors.xml file?
问题描述
我正在使用Eclipse开发一个Android项目.我想使用我在res/values/colors.xml中定义的一种颜色来更改TextView的背景颜色.这些颜色都可以通过使用R.color.color_name来获得.
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.
我的问题是,这根本行不通.更改为我定义的颜色之一始终会使TextView的背景设置为其默认颜色,在这种情况下为黑色.如果我使用Java的内置颜色之一,则效果很好.我认为这是一个颜色定义问题,涉及到我实际上如何在XML中定义颜色的问题,但是我不确定.
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>
推荐答案
它不起作用,因为您正在将背景颜色设置为键本身(这是一个十六进制值,如 0x7f050008
)而不是它的价值.要使用它的价值,请尝试:
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));
这篇关于如何使用在values/colors.xml文件中定义的颜色更改TextView的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!