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

Phi*_*uth 6 android textview

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

Bos*_*one 19

实际上这更容易:

weight2.setBackgroundResource(R.color.darkgrey);
Run Code Online (Sandbox Code Playgroud)


gon*_*lva 11

它不起作用,因为您将背景颜色设置为键本身(这是十六进制值0x7f050008)而不是其值.要使用它的值,请尝试:

weight2.setBackgroundColor(getResources().getColor(R.color.darkgrey));
Run Code Online (Sandbox Code Playgroud)