Java 从字符串值设置Android图像

Java 从字符串值设置Android图像,java,android,imageview,android-imageview,Java,Android,Imageview,Android Imageview,目前,我正在Android应用程序中绘制PNG图像,如下所示: ImageView image = new ImageView(context); image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage)) 如果我在数据库中有一个图像名称列表,有没有一种方法可以使用图像名称设置上面的drawable?我已经有代码通过数据库,我只是想根据从这里获取的值绘制图像 例如,数据库的记录: ID:

目前,我正在Android应用程序中绘制PNG图像,如下所示:

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))
如果我在数据库中有一个图像名称列表,有没有一种方法可以使用图像名称设置上面的drawable?我已经有代码通过数据库,我只是想根据从这里获取的值绘制图像

例如,数据库的记录:

ID:    Name:    ImageName:
-      Test     testimage
因此,当我读取此记录时,我有一个值为“testimage”的字符串,然后我想将图像drawable设置为
R.drawable.testimage

我想到的一种方法是这样的:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;
然而,这不是很有效


谢谢

有一种方法可以做到这一点,您可以使用Resources.getIdentifier()通过字符串检索资源ID

比如:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
我正在使用:

int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);
“testimage”-对应于例如testimage.jpg,即不包括“.jpg”

“drawable”-是资源类型,如:@drawable/testimage


选中“将图像放入资源/文件夹并打开”

image.setImageURI("file:///android_asset/" + nameFromDB);
String path=“sdcard/camera\u app/name.jpg”;
img.setImageDrawable(Drawable.createFromPath(path))

int resId=getResources().getIdentifier(“testimage”,“drawable”,mainActivity.getPackageName());位图图像=BitmapFactory.decodeResource(getResources(),resId);嘘,是的!这是完美的。没有任何解释,这是没有帮助的。您可以为不同的图像使用路径示例字符串path=“sdcard/camera\u app/image1.jpg”;或者String path=“sdcard/camera\u app/image2.jpg”这可以在if-else条件下使用,以便仅绘制您想要的图像。