2013-05-04 45 views
44

中通過名稱訪問可繪製資源在我的應用程序中,我需要獲取一些位圖drawables,我不想保留引用R。所以我創建了一個類DrawableManager來管理drawable。如何在android

public class DrawableManager { 
    private static Context context = null; 

    public static void init(Context c) { 
     context = c; 
    } 

    public static Drawable getDrawable(String name) { 
     return R.drawable.? 
    } 
} 

然後我想通過名稱被拉伸的地方像這樣(的car.png就是把RES /可繪里):

Drawable d= DrawableManager.getDrawable("car.png"); 

但是你可以看到,我無法訪問名稱的資源:

public static Drawable getDrawable(String name) { 
    return R.drawable.? 
} 

任何替代品?

回答

109

請注意,您的方法幾乎總是做錯事的方法(最好將上下文傳遞到使用drawable的對象本身,而不是保持靜態的Context)。

鑑於這種情況,如果你想要做動態加載繪製,您可以使用getIdentifier

Resources resources = context.getResources(); 
final int resourceId = resources.getIdentifier(name, "drawable", 
    context.getPackageName()); 
return resources.getDrawable(resourceId); 
+1

'更好地傳遞上下文到正在使用該繪製比保持靜態上下文somewhere'嗨對象本身,你能告訴我嗎? – hguser 2013-05-04 02:12:42

+1

@hguser - 你想要一個'Drawable'的原因是將它顯示在屏幕上 - 每個視圖/活動/片段都有一個與其關聯的'Context' - 將'Context'傳遞到'getDrawable'方法中。 – ianhanniballake 2013-05-04 02:16:29

+0

謝謝,我明白了。 – hguser 2013-05-04 02:17:41

20

你可以做類似this.-

public static Drawable getDrawable(String name) { 
    Context context = YourApplication.getContext(); 
    int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName()); 
    return context.getResources().getDrawable(resourceId); 
} 

爲了訪問從上下文任何地方,您可以擴展應用程序類別.-

public class YourApplication extends Application { 

    private static YourApplication instance; 

    public YourApplication() { 
     instance = this; 
    } 

    public static Context getContext() { 
     return instance; 
    } 
} 

並將它映射到您的Manifestapplication標籤

<application 
    android:name=".YourApplication" 
    .... 
+3

謝謝,我從來不知道我可以通過這種方式獲得上下文。它似乎會使代碼更清潔。 – hguser 2013-05-04 02:18:43

+0

以這種方式獲得'Context',而不是通過它,這對可測試性來說是不利的。例如,爲了測試任何調用'YourApplication.getContext()'的方法,測試必須首先實例化'YouApplication',以使'YourApplication.getContext()'不返回null。以靜態形式創建全局變量通常是一種不好的做法。 – spaaarky21 2017-02-16 21:38:05

4

修改圖像內容:

ImageView image = (ImageView)view.findViewById(R.id.imagenElement); 
    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName()); 
    image.setImageResource(resourceImage);