dynamic Bitmap drawable in android

狂风中的少年 提交于 2019-12-11 07:08:18

问题


I am wondering how i can set a Bitmap drawable resource from a dynamic variable that is the image name/ type string:

public CustomIcon getView(int position, View convertView, ViewGroup parent) {
        String label;
        String image;
        DataBaseManager db = new DataBaseManager(context);
        label = db.getIconLabel(mIcons.get(position));
        image = db.getIconImage(mIcons.get(position));
        Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                parent.getResources().getIdentifier(image, "drawable", getApplicationContext().getPackageName()));
        Log.v(TAG, "current pos:"+ position);
        CustomIcon icon = new CustomIcon(context, bitmap,label);

        return icon;
    }

the part in question is

Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                         R.drawable.[image]);

CODE CHANGED ABOVE -


回答1:


The way to deal with this is to get the resource ID first and then use the BitmapFactory method:

String imgName = "myicon";
int resID = parent.getResources().getIdentifier(imgName, "drawable", "my.app.package.name");
Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(), resID);


来源:https://stackoverflow.com/questions/9621540/dynamic-bitmap-drawable-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!