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

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 26 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
  • 链接地址: http://www.djcxy.com/p/61730.html

    上一篇: 跟踪全局鼠标事件以进行拖放处理

    下一篇: int从颜色资源