【发布时间】: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)) -
这对威廉有效。谢谢你。请将其作为答案发布,以便我接受。