how can i get the value of a color resource in my activity
Asked Answered
D

5

8

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?

Divest answered 26/5, 2011 at 19:57 Comment(0)
N
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);
Nevsa answered 26/5, 2011 at 20:16 Comment(1)
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
C
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));
Connelly answered 10/12, 2015 at 14:47 Comment(0)
R
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).

Raised answered 26/5, 2011 at 20:2 Comment(0)
C
1
Integer.toHexString(ContextCompat.getColor(context, R.color.black) & 0x00ffffff);

from: Android get color as string value

Crosseyed answered 9/5, 2017 at 17:23 Comment(0)
S
0
int colorResInt = getResources().getColor(R.color.your_color);
String colorHex = String.format("#%06X", 0xFFFFFF & colorInt)

this will handle the alpha value as well

Scrod answered 26/5, 2024 at 9:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.