How can I get color-int from color resource?

ataulm picture ataulm · Mar 11, 2011 · Viewed 365.6k times · Source

Is there any way to get a color-int from a color resource?

I am trying to get the individual red, blue and green components of a color defined in the resource (R.color.myColor) so that I can set the values of three seekbars to a specific level.

Answer

sat picture sat · Mar 11, 2011

You can use:

getResources().getColor(R.color.idname);

Check here on how to define custom colors:

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

EDIT(1): Since getColor(int id) is deprecated now, this must be used :

ContextCompat.getColor(context, R.color.your_color);

(added in support library 23)

EDIT(2):

Below code can be used for both pre and post Marshmallow (API 23)

ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme