如何改变一个TextView的背景颜色与我的价值观/ colors.xml文件中定义的颜色?我的、颜色、价值观、定义

2023-09-06 03:28:18 作者:爷单身、却潇洒

我正在使用Eclipse的Andr​​oid项目。我想改变使用我在RES /价值/ colors.xml定义的颜色之一,一个TextView的背景色。这些颜色都可以使用通过R.color.color_name。

我的问题是,这根本行不通。改变到我的定义颜色之一总是离开的TextView的背景设置为它的默认颜色,在这种情况下,黑色的。如果我使用Java的内置颜色之一,它工作正常。我想这是一个颜色定义的问题,一些涉及如何其实我定义我的XML我的颜色,但我不知道。

  //这工作:
weight1.setBackgroundColor(Color.BLACK);

//这不能正常工作:
weight2.setBackgroundColor(R.color.darkgrey);

//颜色定义:(这是一个单独的XML文件,而不是在我的Java code)
<颜色名称=darkgrey>#A9A9A9< /彩色>
 

解决方案

这是行不通的,因为你设置背景颜色的按键本身(这就像一个十六进制值 0x7f050008 )。要使用它的价值,请尝试:

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

怎样更改桌面背景颜色 指定图片作桌面背景

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>

解决方案

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));