Home » Android » android – Get color resource as string

android – Get color resource as string

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&Answers:

I think you missed #

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

Answer:

Updated answer:

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

Answer:

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

Answer:

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

Try this

Answer:

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