设置Android的图像从字符串值 [英] Setting Android images from string value
问题描述
目前我画一个PNG图像在我的Android应用程序,像这样:
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))
如果我有一个数据库映像名称的列表,有没有一种方法来设置上面使用图像的名称绘制?我已经有code要通过数据库,我只是在寻找基于从这里获取的值来绘制图像。
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
所以,当我在读这条记录,我有一个字符串testimage的值,然后我想的图像绘制设置为 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!
感谢
推荐答案
有这样做,你可以通过字符串中使用Resources.getIdentifier()<一retreive资源ID的方法href="http://developer.android.com/reference/android/content/res/Resources.html">http://developer.android.com/reference/android/content/res/Resources.html
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
是这样的:
int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
这篇关于设置Android的图像从字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!