从R.color编程检索颜色返回错误的颜色 [英] Retrieving color programmatically from R.color returns wrong colors

查看:474
本文介绍了从R.color编程检索颜色返回错误的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想参加一个用户的XML文件中列出的颜色名称,并返回十六进制颜色。我现在用的是code基于该职位<一个href=\"http://stackoverflow.com/questions/26584922/retrieve-color-programmatically-from-r-color\">Retrieve从R.color 编程的颜色。我知道我靠近,因为当我在哈希映射的名字作为键,它正在一小部分的颜色,但在300的颜色在该文件中,寻找5或6好像浪费了处理时间。下面的code是什么被使用过,但如果需要,我可以包括更多。

I am trying to take color names listed in a user's xml file and return the hexadecimal color. I am using the code based off the post Retrieve color programmatically from R.color. I know I am close because when I had a small set of colors in hash map with the names as keys it was working, but over 300 colors in the file and looking for 5 or 6 seems like wasted processing time. The code below is what is being worked with, but I can include more if needed.

用户的XML文件示例。

Example of user's xml file.

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

colors.xml

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

当我运行这个作为调试给出的结果如下:

When I run this as debug the results given are as follows:

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。

The integer that should be returned for green should be -16744448, not 2131099743.

如何,如果可能的话,我取了个名字作为一个字符串并匹配它并返回colors.xml列出的颜色?

How, if possible, do I take a name as a string and match it and return a color listed in colors.xml?

推荐答案

这是颜色的ID,而不是本身的颜色。为了得到你所需要的颜色 getResources()的getColor(field.getInt(NULL)); 而不是

That is the id of the colour, not the colour itself. To get the colour you need getResources().getColor(field.getInt(null)); instead.

研究一切都是一个ID。这就是为什么我们有像的getColor 方法或 getDrawable 这需要作为参数 R.color。 my_color的 R.drawable.my_drawable

Everything on R is an ID. That is why we have methods like getColor or getDrawable which take as argument R.color.my_color or R.drawable.my_drawable.

这篇关于从R.color编程检索颜色返回错误的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆