2014-02-08 41 views
1

我在繪製文件夾中四個畫面:small_blue.jpg,small_green.jpg,big_blue.jpg和big_green.jpg檢索其名稱與功能的可繪製資源參數

我創建了一個函數有兩個參數:

public Bitmap getPic (String size, String color) 
{ 
    return BitmapFactory.decodeResource(getResources(), R.drawable.small_blue); 
} 

我需要R.drawable.small_blue改變small_blue與功能 的參數,但我不能這樣做:

R.drawable. + size + "_" + color 

它是如何完成的?

非常感謝

回答

1

試試這個:

public Bitmap getPic (String size, String color) 
{ 
    return 
     BitmapFactory.decodeResource 
     (
      getResources(), getResourceID(size + "_" + color, "drawable", getApplicationContext()) 
     ); 
} 

protected final static int getResourceID 
(final String resName, final String resType, final Context ctx) 
{ 
    final int ResourceID = 
     ctx.getResources().getIdentifier(resName, resType, 
      ctx.getApplicationInfo().packageName); 
    if (ResourceID == 0) 
    { 
     throw new IllegalArgumentException 
     (
      "No resource string found with name " + resName 
     ); 
    } 
    else 
    { 
     return ResourceID; 
    } 
} 
+0

真棒,非常感謝你! –

+0

;)我也在我的應用程序中使用此代碼。 –