2015-09-05 31 views
7

我想上一个颜色资源使用Color.parseColor()获取颜色资源作为字符串

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

我已经试过这一点,但它给了我错误未知颜色

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

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

回答

16

我想你错过

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

不错观察 –

+3

'Integer.toHexString(ContextCompat.getColor(背景下,R.color.redish)'用最新版本的这个工作对我来说。 –

+1

的getColor我不赞成... [详细](http://stackoverflow.com/questions/31590714/getcolorint-ID弃用-上的Android-6-0-棉花糖API-23) – LukTar

1

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

试试这个

+1

'型string'错误的预期的资源:http://i.imgur.com/zbcdqhL.png – user5294977

+0

再次检查我的回答......! – koutuk

+0

仍然收到错误。什么是你的颜色XML? http://i.imgur.com/R11rsUX.png – user5294977

2
context.getResources().getColor(R.color.redish)); 
+0

'context'需要在那里......它在一个适配器内。 – user5294977

+0

新增。检查这个 –

+2

这就是我在我的问题中的确切内容,它不起作用... – user5294977

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

如果你在活动中使用代码,你可以省略'context'的使用。

+0

这里做的另一种方式:HTTP://stackoverflow.com/questions/13388493/how-can-i-convert-the-android-resources-int-to-a-string-eg-android-r-string -c/43621406#43621406 – user2288580

2

更新答案:

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

这对接受的答案没有帮助。谢谢! – nope4561759