从颜色资源获取color-int [英] Get color-int from color resource

查看:745
本文介绍了从颜色资源获取color-int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从颜色资源中获取color-int?
我试图获取资源(R.color.myColor)中定义的颜色的各个红色,蓝色和绿色组件,以便我可以将三个seekbars的值设置为特定级别。

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.

有关可能有助于在搜索结果中显示此问题的另一个用例的更多信息,我想将alpha应用于定义的颜色我的资源。使用@ sat的正确答案:

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


推荐答案

您可以使用:

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):
由于 getColor(int id)现在已过时,必须使用:

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

(在支持库23中添加)

(added in support library 23)

EDIT(2):

以下代码可用于Marshmallow之前和之后(API 23)

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

这篇关于从颜色资源获取color-int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆