Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get color as string value

Tags:

android

colors

People also ask

How do I get color resources in Android?

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


This is your answer

colorStr=getResources().getString(R.color.someColor);

you will get

 colorStr = "#123456"

Just for the sake of easy copypasta:

"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color));

Or if you want it without the transparency:

"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color) & 0x00ffffff);

All of the solutions here using Integer.toHexString() break if you would have leading zeroes in your hex string. Colors like #0affff would result in #affff. Use this instead:

String.format("#%06x", ContextCompat.getColor(this, R.color.your_color) & 0xffffff)

or with alpha:

String.format("#%08x", ContextCompat.getColor(this, R.color.your_color) & 0xffffffff)

The answers provided above are not updated.

Please try this one

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.dark_sky_blue) & 0x00ffffff);

Cause getResources().getColor need api > 23. So this is better: Just for the sake of easy copy & paste:

Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) );

Or if you want it without the transparency:`

Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) & 0x00ffffff );


It works for me!

String.format("#%06x", ContextCompat.getColor(this, R.color.my_color) & 0xffffff)

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!