android - 在android中可绘制的动态位图

标签 android android-resources

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

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

上面的代码已更改 -

最佳答案

处理方法是先获取资源ID,再使用BitmapFactory方法:

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

关于android - 在android中可绘制的动态位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9621540/

相关文章:

android - 音频无法在android中播放。 android.content.res.Resources $ NotFoundException:资源ID#0x0

android - 如何在 Android Emulator 中禁用 Internet 连接?

android - 为什么在进行无响应 HTTP Post 时线程池会填满?

android - 如何确定应用程序是否在库存 ROM 上运行

android - 在代码中引用字符串变量时出现 java.lang.NullPointerException

java - 如何获得中性按钮的标准颜色

java - 使用列表中资源中的字符串。

android - 将 Android 应用中的语言更改为不受支持的语言

java - 在 Android 和 Java 中加密/解密字符串的不同值

android - ScrollView 切断顶部并在底部留出空间