Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get color-int from color resource?

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.

like image 314
ataulm Avatar asked Mar 11 '11 09:03

ataulm


People also ask

What can I use instead of getColor?

you can use the ContextCompat. getColor() which is part of the Support V4 Library (so it will work for all the previous API).

What color formats are supported for color resources?

red(int) to extract the red component. green(int) to extract the green component. blue(int) to extract the blue component.


2 Answers

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 
like image 197
sat Avatar answered Sep 24 '22 23:09

sat


Based on the new Android Support Library (and this update), now you should call:

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

According to the documentation:

public int getColor (int id) 

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id):

You have to change it like this:

ContextCompat.getColorStateList(getContext(),id); 

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

val color = ContextCompat.getColor(   closestView.context,   R.color.name.color ) 

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Nick Butcher - Droidcon Berlin - Developing Themes with Style

like image 32
Ultimo_m Avatar answered Sep 25 '22 23:09

Ultimo_m