532

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.

ataulm
  • 15,195
  • 7
  • 50
  • 92

13 Answers13

1070

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
Quantum_VC
  • 185
  • 13
sat
  • 40,138
  • 28
  • 93
  • 102
  • 9
    what about android.R.color.some_color :-( – Blundell Jun 18 '12 at 14:29
  • 19
    @Blundell uhh, dunno if you need it now but this works for `android.R.color.some_color` too e.g.: `getResources().getColor(android.R.color.holo_blue_bright)` (at least, on API 17) – ataulm Jul 01 '13 at 18:25
  • How is the performance of this? Is it worth caching the result so I don't have to look it up every time, or does Android do that internally? – karl Mar 20 '14 at 16:39
  • 1
    @karl don't prematurely optimise. It's not a long running operation, and given the param is an ID, it's likely a simple lookup. [Resources src](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/content/res/Resources.java) if you wanted to have a look – ataulm Mar 26 '14 at 19:55
  • @RestInPeace extract it to a method `int getMyColor() { ... }`. You can keep the color in a variable if the verbosity is impacting clarity of your code - I wouldn't do it for performance reasons though – ataulm Sep 02 '14 at 11:09
  • 1
    This call was deprecated in API23. But, you can call `getResources().getColor(R.color.idname, null);` instead – w3bshark Sep 12 '15 at 17:39
  • 36
    getColor() is now deprecated, you can use: ContextCompat.getColor(context, R.color.your_color); – Ricardo Nov 19 '15 at 15:45
  • 2
    I realize you aren't the one who made the edits, but what is the difference between `ContextCompat` and `ResourcesCompat`? If there is no practical difference, it would be less confusing if you removed one of them from your answer. – Suragch Nov 01 '16 at 07:12
  • 21
    Why does Google feel the need to deprecate a perfectly good function for that awful app compact library. It sucks, have both. – Andrew S Nov 18 '16 at 18:23
  • @Andrew I agree. Especially since I am using APKBuilder which doesnt have any support or compatibility libraries. –  Aug 30 '19 at 15:10
  • 10
    I am perpetually in awe of the atrociousness of this platform... at a loss for words. – FranticRock Feb 17 '20 at 17:13
  • getResources().getColor(R.color.your_color) is now deprecated. You might use getColor(R.color.your_color) directly – Anuj Sep 17 '22 at 23:20
129

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

Ultimo_m
  • 4,724
  • 4
  • 38
  • 60
  • 11
    For those wondering what to fill in as the theme in the new method, `Theme` can be passed as null, so just call `getColor(R.color.my_color, null)` if you're unsure what theme to pass in. – w3bshark Sep 12 '15 at 17:42
  • hmm... this is what everyone says but i can't get it to work. Do i have to initialize context? Currently I get "cannot resolve symbol 'context'" – Caio Mar Sep 27 '17 at 18:06
  • To make sure that you are doing it right, try calling it inside the onCreate of the activity, than to get context you need to call getContext() or just "this" – Ultimo_m Sep 27 '17 at 18:11
42

Define your color

values/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- color int as #AARRGGBB (alpha, red, green, blue) -->
    <color name="orange">#fff3632b</color>
    ...
    <color name="my_view_color">@color/orange</color>

</resources>

Get the color int and set it

int backgroundColor = ContextCompat.getColor(context, R.color.my_view_color);
// Color backgroundColor = ... (Don't do this. The color is just an int.)

myView.setBackgroundColor(backgroundColor);

See also

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    can you only use `getResources()` in an `Activity` or `Fragment` ? – Zapnologica Jul 08 '15 at 07:04
  • 2
    @Zapnologica, see the answers to [this question](http://stackoverflow.com/questions/7666589/using-getresources-in-non-activity-class) for thoughts on using `getResources()` outside of an Activity or Fragment. – Suragch Jul 08 '15 at 15:01
  • 1
    @Zapnologica no. `getResources()` is also available as a public API on anything implementing Context and also on Views. – ataulm Aug 11 '15 at 22:30
12

Found an easier way that works as well:

Color.parseColor(getString(R.color.idname));
geckoflume
  • 399
  • 7
  • 11
  • 2
    Interesting, didn't realise you could get the color as a string in this way. I don't think it's easier, but it's interesting – ataulm Apr 19 '20 at 14:05
10

Best Approach

As @sat answer, good approach for getting color is

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

or use below way when you don't have access to getResources() method.

Context context  = getContext(); // like Dialog class
ResourcesCompat.getColor(context.getResources(), R.color.your_color, null);

What i do is

public void someMethod(){
    ...
    ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
}

It is most simple to use anywhere in your app! Even in Util class or any class where you don't have Context or getResource()

Problem (When you don't have Context)

When you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() without Context.
}

Now you will pass Context as a parameter in this method and use getResources().

public void someMethod(Context context){
    ...
    context.getResources...
}

So here is a Bonus unique solution by which you can access resources from anywhere like Util class . Add Resources to your Application class or Create one if does not exist.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

Add name field to your manifest.xml <application tag. (If not added already)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go. Use ResourcesCompat.getColor(App.getRes(), R.color.your_color, null); anywhere in app.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
8

If your current min. API level is 23, you can simply use getColor() like we are using for getString():

//example
textView.setTextColor(getColor(R.color.green));
// if context is not available(ex: not in activity) use with context.getColor()

If you want below API level 23, just use this:

textView.setTextColor(getResources().getColor(R.color.green));

But note that getResources().getColor() is deprecated in API Level 23. In that case replace above with:

textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`

ContextCompat: Helper for accessing features in Context

If You want, you can constraint with SDK_INT like below:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}
Blasanka
  • 21,001
  • 12
  • 102
  • 104
6

I updated to use ContextCompat.getColor(context, R.color.your_color); but sometimes (On some devices/Android versions. I'm not sure) that causes a NullPointerExcepiton.

So to make it work on all devices/versions, I fall back on the old way of doing it, in the case of a null pointer.

try {
    textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
}
catch(NullPointerException e) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
    }
    else {
        textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
    }
}
ninjachippie
  • 410
  • 1
  • 5
  • 14
  • why not use the old version in all cases, or if you are checking the version anyway, use the new API `Resources.getColor(int, Theme)` if you can? You should not catch runtime exceptions. – ataulm Mar 09 '16 at 20:42
  • Just OCD I suppose. ContextCompat, to me seems to be the future proof way of doing it, and therefore the right way. So my approach is, do it the right way. And if that fails (on old devices or whatever), do it the old way. Why should I not catch exceptions at runtime? – ninjachippie Mar 10 '16 at 14:33
2

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)
);
ataulm
  • 15,195
  • 7
  • 50
  • 92
1
ContextCompat.getColor(context, R.color.your_color);

in activity

ContextCompat.getColor(actvityname.this, R.color.your_color);

in fragment

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

for example:

tvsun.settextcolour(ContextCompat.getColor(getActivity(), R.color.your_color))
lue
  • 449
  • 5
  • 16
indrajeet jyoti
  • 431
  • 6
  • 8
0

Accessing colors from a non-activity class can be difficult. One of the alternatives that I found was using enum. enum offers a lot of flexibility.

public enum Colors
{
  COLOR0(0x26, 0x32, 0x38),    // R, G, B
  COLOR1(0xD8, 0x1B, 0x60),
  COLOR2(0xFF, 0xFF, 0x72),
  COLOR3(0x64, 0xDD, 0x17);


  private final int R;
  private final int G;
  private final int B;

  Colors(final int R, final int G, final int B)
  {
    this.R = R;
    this.G = G;
    this.B = B;
  }

  public int getColor()
  {
    return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
  }

  public int getR()
  {
    return R;
  }

  public int getG()
  {
    return G;
  }

  public int getB()
  {
    return B;
  }
}
Confuse
  • 5,646
  • 7
  • 36
  • 58
0

Most Recent working method:

getColor(R.color.snackBarAction)
zedlabs
  • 523
  • 7
  • 18
0

or if you have a function(string text,string color) and you need to pass the Resource Color String you can do as follow

String.valueOf(getResources().getColor(R.color.enurse_link_color))
Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Van Mart
  • 3,002
  • 1
  • 10
  • 5
-2

In kotlin just use this in your activity

R.color.color_name

ex-

mytextView.setTextColor(R.color.red_900)
APP Bird
  • 1,371
  • 1
  • 20
  • 37