ataulm ataulm - 2 months ago 13
Android Question

Get color-int from color resource

Is there a 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.




For more information on another use-case that may help surface this question in search results, I wanted to apply alpha to a color defined in my resources. Using @sat's correct answer:

int alpha = ... // 0-255, calculated based on some business logic
int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
int actionBarBackgroundWithAlpha = Color.argb(
alpha,
Color.red(actionbarBackground),
Color.green(actionbarBackground),
Color.blue(actionbarBackground)
);

sat sat
Answer

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: Since getColor(int id) is deprecated now, this must be used :

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

(added in support library 23)