简体   繁体   English

将十六进制颜色字符串转换回整数

[英]Converting hexadecimal colour string back to integer

Earlier I got the integer value for a colour and converted it to Hexadecimal for storing in a database, now when i read it back and try to convert it back to an integer to use .setBackgroundColor(int) i get the following error 之前我得到一个颜色的整数值,并将其转换为十六进制存储在数据库中,现在当我读回它并尝试将其转换回整数使用.setBackgroundColor(int)我得到以下错误

java.lang.NumberFormatException: Invalid int: "ff0071dc" java.lang.NumberFormatException:无效的int:“ff0071dc”

on this line 在这条线上

items[i].setColourCode(Integer.parseInt(currentJourneys.get(i).getJourneyColourCode(), 16));

Also, if I hardcode in the hex value like this colourLbl.setBackgroundColor(0xff0071dc); 另外,如果我像这个colourLbl.setBackgroundColor(0xff0071dc);那样在十六进制值中进行硬编码colourLbl.setBackgroundColor(0xff0071dc); it works fine 它工作正常

Am I doing something wrong? 难道我做错了什么? How else can i get the hex value out and use it to set the background colour? 我怎么能得到十六进制值并用它来设置背景颜色?

I will recommend Color.parseString() to do it. 我会建议使用Color.parseString()来做到这一点。

Parse the color string, and return the corresponding color-int. 解析颜色字符串,并返回相应的color-int。 If the string cannot be parsed, throws an IllegalArgumentException exception. 如果无法解析字符串,则抛出IllegalArgumentException异常。 Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'. 支持的格式为:#RRGGBB #AARRGGBB或以下名称之一:'red','blue','green','black','white','grey','cyan','magenta','yellow' ,'lightgray','darkgray','grey','lightgrey','darkgrey','aqua','fuchsia','lime','maroon','navy','olive','purple','银','青色'。

http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String) http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)

You have two possibilities to convert a hex representation to int. 您有两种方法可以将hex表示转换为int。

By casting a parsed long to int 通过将解析的long转换为int

int color = (int) Long.parseLong(hex, 16);

or by using a BigInteger to parse the value 或者使用BigInteger来解析值

int color = new BigInteger(hex, 16).intValue();

Some time in the future you might also be able to use the Java 8 method for parsing unsigned int values 将来的某个时候,您也可以使用Java 8方法来解析unsigned int值

int color = Integer.parseUnsignedInt(hex, 16);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM