Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 333
Joe Avatar asked May 26 '11 19:05

Joe


People also ask

How do I get color resources in Android?

Use ResourcesCompat. getColor(App. getRes(), R. color.

What is color resource?

Note: A color is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). As such, you can combine color resources with other simple resources in the one XML file, under one <resources> element.

What is color state list?

A ColorStateList is an object you can define in XML that you can apply as a color, but will actually change colors, depending on the state of the View object to which it is applied.


3 Answers

Assuming you have:

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

And here is code:

int greenColor = getResources().getColor(R.color.green);
String strGreenColor = "#"+Integer.toHexString(greenColor);
like image 52
inazaruk Avatar answered Oct 19 '22 07:10

inazaruk


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

int intColor = getResources().getColor(R.color.your_color);
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
like image 4
Ivo Stoyanov Avatar answered Oct 19 '22 06:10

Ivo Stoyanov


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

like image 3
Ted Hopp Avatar answered Oct 19 '22 05:10

Ted Hopp