Java css 样式的十六进制字符串和 Color.decode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2339994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
css style hex strings and Color.decode
提问by pstanton
this articlesuggests you can use Color c = Color.decode("FF0096");
however this understandably throws an exception
这篇文章建议您可以使用Color c = Color.decode("FF0096");
但是这可以理解地引发异常
Caused by: java.lang.NumberFormatException: For input string: "FF0096"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.valueOf(Integer.java:528)
at java.lang.Integer.decode(Integer.java:958)
at java.awt.Color.decode(Color.java:707)
What is the best way of converting a String in the format of "#FF0096" or "FF0096" into a java awt Color?
将“#FF0096”或“FF0096”格式的字符串转换为java awt Color的最佳方法是什么?
采纳答案by Matthew Flaschen
Color c = Color.decode("0xFF0096");
or
或者
Color c = Color.decode("#FF0096");
or
或者
Color c = new Color(0xFF0096);
回答by codaddict
The Color.decodemethod throws the NumberFormatExceptionif the specified string cannot be interpreted as a decimal, octal, or hexidecimal integer
该Color.decode方法抛出NumberFormatException异常如果指定的字符串不能被解释为十进制,八进制,十六进制或整数
The string "FF0096" withoutthe prefix of 0
or 0x
will be interpreted as a base 10 representation which does not work.
没有前缀0
或的字符串“FF0096”0x
将被解释为不起作用的基数 10 表示。
回答by Ehtesh Choudhury
I was looking for a similar way to do this in Android. For some reason, I couldn't find Color.decode()
so I looked for an alternative. If you want to use a hex string to represent a color in Android, you can do the following:
我正在寻找一种类似的方法来在 Android 中执行此操作。出于某种原因,我找不到,Color.decode()
所以我寻找替代方案。如果要在 Android 中使用十六进制字符串来表示颜色,可以执行以下操作:
String hexColor = "#142b44";
View row = findViewById(R.id.row);
int color = Color.parseColor(hexColor);
row0.setBackgroundColor(color);
More at Color#parseColor