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:

  • DefaultHttpClient to AndroidHttpClient
  • Twitter Fabric fails to install in Android Studio due to missing dependencies
  • Taking picture from camera without preview
  • How to show the copyright symbol in a Android dialog?
  • Android Launcher app icon not updated to new icon after market update
  • MapActivity: set APIKey programmatically
  • 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)
    );
    

  • How to get real screen height and width?
  • How to capture image from custom CameraView in Android?
  • Android: set just one padding of textview programmatically
  • How to set up compile library in android studio. LOMBOK
  • Tap on screen 5 Times in 3 seconds in android
  • listening to scroll events horizontalscrollview android
  • 5 Solutions collect form web for “Get color-int from color resource”

    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
    

    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);

    Here is a somewhat fuller example (and updated for API 24 and below) :

    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

    • How to set background color of a View
    • Color docs
    • Color Style Design docs

    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));
        }
    }
    

    Use ResourcesCompat.getColor method, though it has rather verbose parameters.

    If you use only one theme in your app, you can simplify referencing colors in code (“How do I get my color now?”) you can use a custom class with all specific Android-framework approaches inside. Use it like myView.setBackgroundColor(Color.getMyRed()).

    1. In AndroidManifest.xml name your application:

      <application
        android:name="com.my_site.Application"
      ...>
      </application>
      
    2. Create a helper global class for your application at com.my_site path to get context and resources in any static methods:

      import android.content.Context;
      
      public class Application
      extends android.app.Application {
      
        private static Context context;
      
        public static Context getContext() {
      
          return Application.context;
        }
      
        public void onCreate() {
      
          super.onCreate();
          Application.context = getApplicationContext();
        }
      }
      
    3. Create custom Color class with static getter-methods:

      import android.support.v4.content.res.ResourcesCompat;
      import com.my_site.mobile.R;
      
      /**
       * Simplify getting colors.
       */
      public class Color {
      
        public static int getMyRed() {
      
          return
            ResourcesCompat.getColor(
              com.my_site.Application
                .getContext()
                .getResources(),
              R.color.my_red,
              null);
        }
      }
      
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.