获取颜色资源作为字符串

时间:2015-09-05 05:52:25

标签: android android-xml android-resources

我正在尝试在颜色资源上使用Color.parseColor()

<color name="redish">#FF0000</color>

我试过这个,但它给了我错误未知颜色

Color.parseColor(Integer.toHexString(context.getResources().getColor(R.color.redish)))

如何正确地将颜色资源转换为String

5 个答案:

答案 0 :(得分:18)

我想你错过了

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))

答案 1 :(得分:4)

更新回答:

String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff);

答案 2 :(得分:2)

context.getResources().getColor(R.color.redish));

答案 3 :(得分:1)

String colorString=getResources().getString(R.color.redish);

试试这个

答案 4 :(得分:0)

我有一个存储在对象中的颜色(包含其他字段)。颜色也在xml文件(colors.xml)中定义。
所以想设置textview的背景颜色。我这样做了:

...    
String color= res.colorName; // res is an object
int c = context.getResources().getIdentifier(color,"color", context.getPackageName());
textView.setBackgroundColor(Color.parseColor("#" + Integer.toHexString(context.getResources().getColor(c))));

如果您在活动中使用代码,则可以省略使用“上下文”。

相关问题