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?

5 Answers 5

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

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,
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)); 

Comments

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).

Comments

1
Integer.toHexString(ContextCompat.getColor(context, R.color.black) & 0x00ffffff); 

from: Android get color as string value

Comments

0
int colorResInt = getResources().getColor(R.color.your_color); String colorHex = String.format("#%06X", 0xFFFFFF & colorInt) 

this will handle the alpha value as well

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.