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

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


当前回答

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

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

其他回答

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

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

如果你当前的最小API级别是23,你可以简单地使用getColor(),就像我们使用getString()一样:

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

如果你想要低于API级别23,只需使用这个:

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

但请注意,getResources(). getcolor()在API级别23中已弃用。在这种情况下,将上面的替换为:

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

ContextCompat:用于访问Context中的特性的Helper

如果你愿意,你可以像下面这样约束SDK_INT:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

关于另一个用例的更多信息可能有助于在搜索结果中显示这个问题,我想将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)
);
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))

或者如果你有一个函数(字符串文本,字符串颜色),你需要传递资源颜色字符串,你可以这样做

String.valueOf(getResources().getColor(R.color.enurse_link_color))