【问题标题】:Retrieving color programmatically from R.color returns wrong colors从 R.color 以编程方式检索颜色返回错误的颜色
【发布时间】:2015-07-06 15:28:49
【问题描述】:

我正在尝试获取用户 xml 文件中列出的颜色名称并返回十六进制颜色。我正在使用基于帖子Retrieve color programmatically from R.color 的代码。我知道我很接近,因为当我在哈希图中有一小组颜色以名称作为键时它正在工作,但是文件中有超过 300 种颜色并寻找 5 或 6 种似乎浪费了处理时间。下面的代码是正在使用的代码,但如果需要,我可以包含更多代码。

用户的xml文件示例。

<Item>
    <Item_Name>Daily</Item_Name>
    <Price>400</Price>
    <Type>Entry</Type>
    <Color>Green</Color>
</Item>

colors.xml

 <color name="green">#008000</color>

Java:

 0   **pass in name from method call**
 1   Class res = R.color.class;
 2   Field field = res.getField( name );
 3   color = field.getInt(null);

当我将其作为调试运行时,给出的结果如下:

0: name = "green"
1: res = tech.travis.poolpos.R$color
2: field = public static final int tech.travis.poolpos.R$color.green
3: color = 2131099743 (integer).  This translates to #&5f00067f,
     which is about a navy blue with an opacity of about 37%.

应该为绿色返回的整数应该是 -16744448,而不是 2131099743。

如果可能,我如何将名称作为字符串进行匹配并返回 colors.xml 中列出的颜色?

【问题讨论】:

  • 我认为这是颜色的 id,而不是颜色本身。要得到你需要的颜色getResources().getColor(field.getInt(null))
  • 这对威廉有效。谢谢你。请将其作为答案发布,以便我接受。

标签: android xml colors


【解决方案1】:

这是颜色的 id,而不是颜色本身。要获得您需要getResources().getColor(field.getInt(null)); 的颜色。

R 上的所有内容都是一个 ID。这就是为什么我们有像getColorgetDrawable 这样的方法,它们将R.color.my_colorR.drawable.my_drawable 作为参数。

【讨论】:

    【解决方案2】:

    resources.getColor 已弃用。获取颜色的新方法是:

    ContextCompat.getColor(context, R.color.color_name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-01
      • 2010-09-13
      • 2014-01-05
      • 2020-11-11
      • 1970-01-01
      • 2019-12-01
      • 2015-12-06
      • 2021-03-31
      相关资源
      最近更新 更多