2014-02-18 50 views
4

我在可繪製文件夾中有很多圖標,並且我將它們的名稱設置爲字符串。如何訪問可繪製文件夾並更改背景imageView(或任何視圖)動態使用這些名稱。由於如何將字符串轉換爲可繪製

回答

21

這是可以做到使用反射:

String name = "your_drawable"; 
final Field field = R.drawable.getField(name); 
int id = field.getInt(null); 
Drawable drawable = getResources().getDrawable(id); 

或者使用Resources.getIdentifier()

String name = "your_drawable"; 
int id = getResources().getIdentifier(name, "drawable", getPackageName()); 
Drawable drawable = getResources().getDrawable(id); 

然後用這個在任何情況下設置繪製:

view.setBackground(drawable) 
+0

我應該使用'view.setBackground(drawable)'或'view.setBackgroundResource(id)'或者什麼? –

+0

我編輯了我的答案。 –

+0

非常感謝。這是工作:)所有的答案都是正確的 –

1

如果你有文件名作爲字符串,你可以使用:

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName()); 

與此ID,您可以訪問它像往常一樣(假定它是一個繪製):

Drawable drawable = getResources().getDrawable(id); 
+0

'id'在這種情況下不起作用。 –

+0

謝謝。這個答案是正確的 –

5

這是可以做到像這樣:

ImageView imageView = new ImageView(this); 
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName()))); 
+0

謝謝。這個答案也對 –

3

試試這個:

public Bitmap getPic (int number) 
{ 
    return 
     BitmapFactory.decodeResource 
     (
      getResources(), getResourceID("myImage_" + number, "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

謝謝。我相信這是真的,但我沒有嘗試:) –

8
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName()); 
Drawable d = YourActivity.this.getResources().getDrawable(resId); 
+0

謝謝。這個答案也是正確的 –

0

使用cas e如果沒有任何活動,使用@FD_例子

注:

,如果你是不是在你必須發送上下文PARAM才能使用的任何活動「getResources()」或「getPackageName()」,和「getDrawable(id)」已棄用,請改用getDrawer(int id,主題主題)。 (主題可爲空):

String name = "your_drawable"; 
int id = context.getResources().getIdentifier(name, "drawable", 
context.getPackageName()); 
Drawable drawable = context.getResources().getDrawable(id, null);