traisjames
traisjames

Reputation: 211

Retrieving color programmatically from R.color returns wrong colors

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.

Example of user's xml file.

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

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%.

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

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

Upvotes: 2

Views: 2932

Answers (2)

HaraldGeroldseck
HaraldGeroldseck

Reputation: 11

resources.getColor is deprecated. the new way to get a color is:

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

Upvotes: 1

William
William

Reputation: 3034

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

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.

Upvotes: 6

Related Questions