【问题标题】:How to change a TextView's background color with a color defined in my values/colors.xml file?如何使用我的 values/colors.xml 文件中定义的颜色更改 TextView 背景颜色?
【发布时间】:2011-02-06 04:36:51
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: android textview


    【解决方案1】:

    其实这样更容易:

    weight2.setBackgroundResource(R.color.darkgrey);
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • getResources().getColor(int) 已弃用。请改用 setBackgroundResource(int)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 2015-07-22
      • 2015-12-17
      相关资源
      最近更新 更多