Android中的資源(如R.color.colorPrimary)實際上表示由資源ID以整數的形式。這不是實際的色值。要獲得顏色值,您可以使用提供的int getColor(int id)
方法。請參閱Android開發者指南中的Accessing Resources。
正確的方式,以節省資源的ID和重複使用的顏色是:
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(COLOR_COLUMN, R.color.colorPrimary);
int resourceId = temp.get(COLOR_COLUMN);
view.setBackgroundColor(getColor(resourceId));
作爲替代方案,你也可以直接保存顏色的整數表示(而不是其資源ID):
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(COLOR_COLUMN, getColor(R.color.colorPrimary));
int color = temp.get(COLOR_COLUMN);
view.setBackgroundColor(color);
如果出於任何原因,你需要的資源的ID保存爲一個字符串,你可以這樣做,當然:
HashMap<Integer, String> temp = new HashMap<>();
temp.put(COLOR_COLUMN, String.valueOf(R.color.colorPrimary));
int resourceId = Integer.parseInt(temp.get(COLOR_COLUMN));
view.setBackgroundColor(getColor(resourceId));
我認爲你的COLOR_COLUMN
變量是一個整數。
請顯示「temp」變量的聲明/初始化 –
爲什麼要將十六進制顏色值解析爲整數?您應該獲取字符串值,然後將十六進制轉換爲彩色。或者設置十六進制顏色 –
(1)如果直接setBackgroundColor(R.color.colorPrimary),會發生什麼? (2)嘗試記錄TextView的背景顏色以與(((ColorDrawable)textView.getBackground())。getColor()'進行比較,在變化之前和之後,該值是否有意義? (3)你真的想在intmap中保留一個字符串嗎?什麼是用例? – orip