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?
how can i get the value of a color resource in my activity
Assuming you have:
<color name="green">#0000ff00</color>
And here is code:
int greenColor = getResources().getColor(R.color.green);
String strGreenColor = "#"+Integer.toHexString(greenColor);
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, –
Bey
If you need just the HEX value (without alpha):
int intColor = getResources().getColor(R.color.your_color);
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
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)
.
Integer.toHexString(ContextCompat.getColor(context, R.color.black) & 0x00ffffff);
int colorResInt = getResources().getColor(R.color.your_color);
String colorHex = String.format("#%06X", 0xFFFFFF & colorInt)
this will handle the alpha value as well
© 2022 - 2025 — McMap. All rights reserved.