Reputation: 165
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
Reputation: 12021
Updated answer:
String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff);
Upvotes: 7
Reputation: 27515
I think you missed #
Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))
Upvotes: 25
Reputation: 832
String colorString=getResources().getString(R.color.redish);
Try this
Upvotes: 2
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