是否可以通过 id 获取 mipmap 图像?

is it possible to get mipmap image by id?

我已将图像图标存储在我的 android 项目的 res/mipmap 文件夹中。他们每个人都有自己的图像 ID。我想通过图像 ID 检查我是否有图像。我想做类似的事情,

String input_id = "blue_image";
ImageView image;
if (image.getImageByID(input_id)){  ## if image with blue_image exists
    image.setImageResource(...);
}

如果我知道 blue_image 存在,那么我通常会得到它

image.setImageResource(R.mipmap.blue_image);

这题好像有2个问题。一个是通过 ID 检查图像是否存在,第二个是在 java.

中找到类似于 getattr() python 函数的东西

如果你有类似情况的其他解决方案,也欢迎提供。

在您的 Activity class 中试试这个:

int imageId = getResources().getIdentifier(inputId, "drawable", getPackageName());

if (imageId > 0) {
    image.setImageResource(imageId);
}

关键是getIdentifier() returns 0 如果找不到资源

使用:

int imageId = getResources().getIdentifier(inputId, "mipmap", getPackageName());

使用 "mimap",而不是 建议的 "drawable"