如何使用在values/colors.xml文件中定义的颜色更改TextView的背景颜色?

6
我正在使用Eclipse开发Android项目,想要使用在res/values/colors.xml中定义的颜色之一来更改TextView的背景颜色。这些颜色都可以通过R.color.color_name访问。
然而,我遇到的问题是这样做根本没有效果。使用我定义的任何颜色都会使TextView的背景保持其默认颜色,即黑色。但如果使用Java内置的颜色,则可以正常工作。我认为这是一个颜色定义问题,可能与我在XML中定义颜色的方式有关,但我并不确定。
// 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>
2个回答

19

实际上,使用这个更加简单:

weight2.setBackgroundResource(R.color.darkgrey);

11

它无法工作是因为你将背景颜色设置为键本身(一个十六进制值,例如0x7f050008),而不是它的值。要使用其值,请尝试:

weight2.setBackgroundColor(getResources().getColor(R.color.darkgrey));

getResources().getColor(int)已被弃用。请改用setBackgroundResource(int)。 - CoolMind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接