[英]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.