第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Android中按名稱訪問可繪制資源

如何在Android中按名稱訪問可繪制資源

溫溫醬 2019-12-27 09:47:36
在我的應用程序中,我需要將一些位圖可繪制對象放置在不想保留reference的位置R。因此,我創(chuàng)建了一個類DrawableManager來管理可繪制對象。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.?    }}然后我想通過類似這樣的名稱來獲取drawable(car.png放在res / drawables里面):Drawable d= DrawableManager.getDrawable("car.png");但是,如您所見,我無法通過名稱訪問資源:public static Drawable getDrawable(String name) {    return R.drawable.?}有其他選擇嗎?
查看完整描述

3 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

請注意,您的方法幾乎總是錯誤的處理方式(最好是將上下文傳遞給使用drawable的對象本身,而不是在Context某個地方保持靜態(tài))。


鑒于此,如果要進行動態(tài)可繪制加載,則可以使用getIdentifier:


Resources resources = context.getResources();

final int resourceId = resources.getIdentifier(name, "drawable", 

   context.getPackageName());

return resources.getDrawable(resourceId);


查看完整回答
反對 回復 2019-12-27
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

你可以做這樣的事情。


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);

}

為了從任何地方訪問上下文,您可以擴展Application類。


public class YourApplication extends Application {


    private static YourApplication instance;


    public YourApplication() {

        instance = this;

    }


    public static Context getContext() {

        return instance;

    }

}

并將其映射到您的Manifest application標簽中


<application

    android:name=".YourApplication"

    ....


查看完整回答
反對 回復 2019-12-27
?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

修改圖片內容:


    ImageView image = (ImageView)view.findViewById(R.id.imagenElement);

    int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());

    image.setImageResource(resourceImage);


查看完整回答
反對 回復 2019-12-27
  • 3 回答
  • 0 關注
  • 614 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號