有没有办法从颜色资源中获得一个color-int ?
我试图获得在资源(R.color.myColor)中定义的颜色的单个红色,蓝色和绿色组件,以便我可以将三个搜索条的值设置为特定级别。
有没有办法从颜色资源中获得一个color-int ?
我试图获得在资源(R.color.myColor)中定义的颜色的单个红色,蓝色和绿色组件,以便我可以将三个搜索条的值设置为特定级别。
当前回答
在kotlin中,只需在您的活动中使用它
R.color.color_name
ex-
mytextView.setTextColor(R.color.red_900)
其他回答
你可以使用:
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
从非活动类中访问颜色可能很困难。我发现的一个替代方法是使用enum。Enum提供了很大的灵活性。
public enum Colors
{
COLOR0(0x26, 0x32, 0x38), // R, G, B
COLOR1(0xD8, 0x1B, 0x60),
COLOR2(0xFF, 0xFF, 0x72),
COLOR3(0x64, 0xDD, 0x17);
private final int R;
private final int G;
private final int B;
Colors(final int R, final int G, final int B)
{
this.R = R;
this.G = G;
this.B = B;
}
public int getColor()
{
return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
}
public int getR()
{
return R;
}
public int getG()
{
return G;
}
public int getB()
{
return B;
}
}
基于新的Android支持库(和这次更新),现在你应该调用:
ContextCompat.getColor(context, R.color.name.color);
根据文档:
public int getColor (int id)
此方法在API级别23中已弃用。 使用getColor(int, Theme)代替
它是相同的解决方案getResources().getColorStateList(id):
你必须像这样改变它:
ContextCompat.getColorStateList(getContext(),id);
编辑2019
关于ThemeOverlay,使用最近视图的上下文:
val color = ContextCompat.getColor(
closestView.context,
R.color.name.color
)
这样你就可以根据你的ThemeOverlay得到正确的颜色。
当你在同一个活动中使用不同的主题时特别需要,比如黑暗/光明主题。如果你想了解更多关于主题和风格的知识,建议听这个演讲:用风格开发主题
如果你当前的最小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));
}
在kotlin中,只需在您的活动中使用它
R.color.color_name
ex-
mytextView.setTextColor(R.color.red_900)