7

i need to get the string value of a color. in other words i want to pull the #ffffffff from a color resource like <color name="color">#ffffffff</color> in string format. is there any way of doing this?

Joe
  • 1,326
  • 7
  • 34
  • 52

4 Answers4

18

Assuming you have:

<color name="green">#0000ff00</color>

And here is code:

int greenColor = getResources().getColor(R.color.green);
String strGreenColor = "#"+Integer.toHexString(greenColor);
inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • This is not a good idea, as Integer.toHexString will not restore the leading zeroes. If you're not using alpha, it will work, as the alpha is set to FF and there are no leading zeroes, but in the example given, strGreen color will be "#ff00", not "#0000ff00" as intended, – Ryan M Jun 12 '14 at 00:30
4

If you need just the HEX value (without alpha):

int intColor = getResources().getColor(R.color.your_color);
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Ivo Stoyanov
  • 16,256
  • 8
  • 62
  • 65
3

You won't be able to pull out the original source text of the XML. That is converted to a binary value at build time. (So, for instance, the difference between #fff and #ffffffff is erased.)

You can convert the color value to a hex string, of course, using Integer.toHexString(int).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0
Integer.toHexString(ContextCompat.getColor(context, R.color.black) & 0x00ffffff);

from: Android get color as string value

Community
  • 1
  • 1
AITAALI_ABDERRAHMANE
  • 2,499
  • 1
  • 26
  • 31