2011-09-25 45 views
16

我想使用變量而不是R.drawable.myimage,因爲我有一個包含圖像名稱的數據庫。我從數據庫中得到名字,我想用這個名字使用drawable資源。使用變量繪製資源

String flagimage = "R.drawable." + myHelper.getFlagImage(5); 
int resourceId = Integer.parseInt(flagimage); 
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId); 

回答

36

可以使用名稱的資源,像

getIdentifier (String name, String defType, String defPackage);

getResources().getIdentifier("us","drawable","com.app"); 

上述函數會返回一個整數值相同R.drawable.us。

這是您如何使用資源名稱進行訪問。

+0

謝謝很多 – Alex

+2

只是一個快速注[則getIdentifier](http://developer.android.com/reference/android/content /res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29)如果未找到此類資源,則返回「0」。 (0不是有效的資源ID。) – razzak

16

您可以使用此代碼來獲取標識...

Resources res = this.getResources(); 
int resID = res.getIdentifier(imagename, "drawable", this.getPackageName()); 
+0

經過大量搜索,它工作起來很順利。謝謝 –