之前我得到了颜色的整数值并将其转换为十六进制以存储在数据库中,现在当我读回它并尝试将其转换回整数以使用.setBackgroundColor(int)
时出现以下错误
java.lang.NumberFormatException:无效的int:“ff0071dc”
在这一行
items[i].setColourCode(Integer.parseInt(currentJourneys.get(i).getJourneyColourCode(), 16));
另外,如果我像这样硬编码十六进制值
colourLbl.setBackgroundColor(0xff0071dc);
它运作正常
我做错了吗?我怎么能得到十六进制值并用它来设置背景颜色?
答案 0 :(得分:2)
我会建议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& #39;,' silver',' teal'。
http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)
答案 1 :(得分:1)
您有两种方法可以将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);