user5294977
user5294977

Reputation: 165

Get color resource as string

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?

Upvotes: 11

Views: 19437

Answers (5)

Darush
Darush

Reputation: 12021

Updated answer:

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

Upvotes: 7

N J
N J

Reputation: 27515

I think you missed #

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))

Upvotes: 25

koutuk
koutuk

Reputation: 832

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

Try this

Upvotes: 2

userAbhi
userAbhi

Reputation: 715

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

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

context.getResources().getColor(R.color.redish));

Upvotes: 2

Related Questions