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?

N J
  • 27,217
  • 13
  • 76
  • 96
user5294977
  • 165
  • 1
  • 2
  • 6

5 Answers5

24

I think you missed #

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))
N J
  • 27,217
  • 13
  • 76
  • 96
  • 3
    `Integer.toHexString(ContextCompat.getColor(context, R.color.redish)` with recent versions this worked for me. – Carlo Espino Feb 18 '16 at 05:39
  • 1
    getColor i deprecated...[more](http://stackoverflow.com/questions/31590714/getcolorint-id-deprecated-on-android-6-0-marshmallow-api-23) – LukaszTaraszka Mar 12 '17 at 10:28
6

Updated answer:

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff);
Darush
  • 11,403
  • 9
  • 62
  • 60
2

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

Try this

mpolat
  • 2,691
  • 2
  • 15
  • 13
koutuk
  • 832
  • 1
  • 8
  • 17
2
context.getResources().getColor(R.color.redish));
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
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' .

userAbhi
  • 695
  • 6
  • 10
  • Here's another way of doing it:http://stackoverflow.com/questions/13388493/how-can-i-convert-the-android-resources-int-to-a-string-eg-android-r-string-c/43621406#43621406 – user2288580 Apr 25 '17 at 21:41