2015-07-28 56 views
1

當給一個片段充氣時,我需要使用從該活動傳入的唯一字符串鍵設置可繪製的ImageView,但這不是以R.drawable的形式。基本上,我需要映射輸入字符串,如:如何從唯一鍵引用可繪製對象

"earth" --> R.drawable.icon_earth 
"mars" --> R.drawable.icon_mars 
"pluto" --> R.drawable.icon_pluto 

我與發現這樣做在Android或連渣一般以正確的方式掙扎。也許我只是沒有以正確的方式搜索SO或Google,但我一直堅持了一個多小時。

謝謝。

回答

1

怎麼樣採取Map<String, Object>這樣的 -

Map<String, Object> map = new HasMap<String, Object>(); 
map.put("earth", R.drawable.icon_earth); 

之後,你可以從中獲取價值Map<String, Object>你聲明 - 使用map.get("earth")

+1

這是我認爲我最終會這樣做的方式。使用'getResources()。getIdentifier()'的其他解決方案似乎更容易,但在getIdentifier文檔中不鼓勵 –

1

map如果使用字符串作爲圖標標識即可使用getIdentifier方法Resources

String resourceName = "icon_" + "earth"; 
int resource = getResources().getIdentifier(resourceName, "drawable", "com.package");