11

I'm trying to use Color.parseColor() on a color resource:

<color name="redish">#FF0000</color> 

I've tried this, but it gives me the error Unknown color:

Color.parseColor(Integer.toHexString(context.getResources().getColor(R.color.redish))) 

How do I convert the color resource to a String properly?

5 Answers 5

25

I think you missed #

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish))) 
Sign up to request clarification or add additional context in comments.

2 Comments

Integer.toHexString(ContextCompat.getColor(context, R.color.redish) with recent versions this worked for me.
getColor i deprecated...more
7

Updated answer:

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff); 

2 Comments

This worked for me when the accepted answer didn't. Thanks!
The accepted answer was not working for me, but this one does! Kudos!
2
context.getResources().getColor(R.color.redish)); 

2 Comments

context needs to be there... it's within an adapter.
where you store your color xml ?
2

String colorString=getResources().getString(R.color.redish); 

Try this

Comments

1

I got a color stored in object (containing other fields). Also the colors were defined in xml file (colors.xml).
So wanted to set the background color of textview. I did it as follows:

... String color= res.colorName; // res is an object int c = context.getResources().getIdentifier(color,"color", context.getPackageName()); textView.setBackgroundColor(Color.parseColor("#" + Integer.toHexString(context.getResources().getColor(c)))); 

If you are using the code in activity you can omit use of 'context' .

1 Comment

Here's another way of doing it:stackoverflow.com/questions/13388493/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.