[英]Converting hexadecimal colour string back to integer
之前我得到一个颜色的整数值,并将其转换为十六进制存储在数据库中,现在当我读回它并尝试将其转换回整数使用.setBackgroundColor(int)
我得到以下错误
java.lang.NumberFormatException:无效的int:“ff0071dc”
在这条线上
items[i].setColourCode(Integer.parseInt(currentJourneys.get(i).getJourneyColourCode(), 16));
另外,如果我像这个colourLbl.setBackgroundColor(0xff0071dc);
那样在十六进制值中进行硬编码colourLbl.setBackgroundColor(0xff0071dc);
它工作正常
难道我做错了什么? 我怎么能得到十六进制值并用它来设置背景颜色?
我会建议使用Color.parseString()
来做到这一点。
解析颜色字符串,并返回相应的color-int。 如果无法解析字符串,则抛出IllegalArgumentException异常。 支持的格式为:#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)
您有两种方法可以将hex
表示转换为int。
通过将解析的long转换为int
int color = (int) Long.parseLong(hex, 16);
或者使用BigInteger
来解析值
int color = new BigInteger(hex, 16).intValue();
将来的某个时候,您也可以使用Java 8方法来解析unsigned int值
int color = Integer.parseUnsignedInt(hex, 16);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.