有没有办法从颜色资源中获得一个color-int ?

我试图获得在资源(R.color.myColor)中定义的颜色的单个红色,蓝色和绿色组件,以便我可以将三个搜索条的值设置为特定级别。


当前回答

你可以使用:

getResources().getColor(R.color.idname);

点击这里查看如何定义自定义颜色:

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

编辑(1): 由于getColor(int id)现在已弃用,必须使用:

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

(在支持库23中添加)

编辑(2):

以下代码可用于棉花糖前和后(API 23)

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

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme

其他回答

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

在活动

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

在片段

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

例如:

tvsun.settextcolour(ContextCompat.getColor(getActivity(), R.color.your_color))

关于另一个用例的更多信息可能有助于在搜索结果中显示这个问题,我想将alpha应用于我的资源中定义的颜色。

使用@sat的正确答案:

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

找到了一个更简单的方法:

Color.parseColor(getString(R.color.idname));

你可以使用:

getResources().getColor(R.color.idname);

点击这里查看如何定义自定义颜色:

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

编辑(1): 由于getColor(int id)现在已弃用,必须使用:

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

(在支持库23中添加)

编辑(2):

以下代码可用于棉花糖前和后(API 23)

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

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme

最近工作方法:

getColor(R.color.snackBarAction)