android中的动态Bitmap drawable

时间:2012-03-08 16:53:01

标签: android android-resources

我想知道如何从动态变量(图像名称/类型字符串)设置Bitmap可绘制资源:

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

有问题的部分是

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

上面的代码更改 -

1 个答案:

答案 0 :(得分:1)

处理此问题的方法是首先获取资源ID,然后使用BitmapFactory方法:

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