19

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

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

如果我在数据库中有图像名称列表,有没有办法使用图像名称设置上面的可绘制对象?我已经有了通过数据库的代码,我只是想根据从这里获取的值来绘制图像。

例如,数据库的记录:

ID:    Name:    ImageName:
-      Test     testimage

因此,当我阅读此记录时,我有一个值为“testimage”的字符串,然后我想将可绘制的图像设置为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;

但是,这不是很有效!

谢谢

4

4 回答 4

26

有一种方法可以做到这一点,您可以使用 Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html通过字符串检索资源 ID

就像是:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
于 2010-11-30T11:10:13.100 回答
22

我正在使用:

int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);

“testimage” - 对应于例如 testimage.jpg,即不包括“.jpg”

"drawable" - 是资源类型,例如:@drawable/testimage

检查Resources.getIdentifier(...)

于 2010-11-30T11:15:57.390 回答
0

将图像放入 assets/ 文件夹并打开

image.setImageURI("file:///android_asset/" + nameFromDB);
于 2010-11-30T11:18:29.393 回答
-2

字符串路径 = "sdcard/camera_app/name.jpg"; img.setImageDrawable(Drawable.createFromPath(path));

于 2016-08-02T18:19:51.257 回答