If i defined a color in resources
#123456
it\'s possible
For API above 21 you can use
getString(R.color.color_name);
This will return the color in a string format. To convert that to a color in integer format (sometimes only integers are accepted) then:
Color.parseColor(getString(R.color.color_name));
The above expression returns the integer equivalent of the color defined in color.xml file
The answers provided above are not updated.
Please try this one
String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff);
I don't think there is standard functionality for that. You can however turn the return in value from getColor()
to hex and turn the hex value to string.
hex 123456 = int 1193046;
This is how I've done it:
String color = "#" + Integer.toHexString(ContextCompat.getColor
(getApplicationContext(), R.color.yourColor) & 0x00ffffff);
If you don't want to use ContextCompat
or SuppressLint
, simply add a string
resource right under your color
.
Instead of
<color name="text_color">#FFFFFF</color>
Use
<color name="text_color">#FFFFFF</color>
<string name="text_color_string">#FFFFFF</string>
Your code does get more repetitive but it's much cleaner. Besides, forgeting to updating the string
after changing color
is almost impossible since they are right next to each other.
This is your answer
colorStr=getResources().getString(R.color.someColor);
you will get
colorStr = "#123456"