从字符串值设置 Android 图像 [英] Setting Android images from string value

查看:36
本文介绍了从字符串值设置 Android 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

例如,数据库的一条记录:

ID: 名称: 图像名称:- 测试 testimage

因此,当我阅读此记录时,我有一个值为testimage"的字符串,然后我想将可绘制的图像设置为 R.drawable.testimage.>

我想这样做的一种方式是这样的:

int image = R.drawable.blank;//空白图片//testimage.png 是数据库中的图片名称if(imageName.toString().equals("testimage.png"))图像 = R.drawable.testimage;else if(imageName.toString().equals("another.png"))图像 = R.drawable.another;否则 if(imageName.toString().equals("etc.png"))图像 = R.drawable.etc;

但是这样效率不高!

谢谢

解决方案

有一种方法可以做到这一点,您可以使用 Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html

类似于:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");

Currently I'm drawing a PNG image in my Android application like so:

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

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

ID:    Name:    ImageName:
-      Test     testimage

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

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;

However this isn't very efficient!

Thanks

解决方案

There is a method for doing that, you can retreive resource IDs by string using Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html

Something like:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");

这篇关于从字符串值设置 Android 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆