简体   繁体   中英

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

java.lang.NumberFormatException: Invalid 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); 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.

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. 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'.

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

You have two possibilities to convert a hex representation to int.

By casting a parsed long to int

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

or by using a BigInteger to parse the value

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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