Java 从字符串值设置 Android 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4313007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Android images from string value
提问by ingh.am
Currently I'm drawing a PNG image in my Android application like so:
目前我正在我的 Android 应用程序中绘制一个 PNG 图像,如下所示:
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
.
因此,当我阅读此记录时,我有一个值为“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!
然而,这不是很有效!
Thanks
谢谢
采纳答案by GeekYouUp
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
有一种方法可以做到这一点,您可以使用 Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html通过字符串检索资源 ID
Something like:
就像是:
int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
回答by Erik S
I'm using:
我正在使用:
int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);
"testimage" - corresponds to for instance testimage.jpg, i.e. dont include ".jpg"
“testimage” - 对应于例如 testimage.jpg,即不包含“.jpg”
"drawable" - is the resource type, like in: @drawable/testimage
"drawable" - 是资源类型,如:@drawable/testimage
回答by Mikpa
Put you images in the assets/ folder and open
将您的图像放在 assets/ 文件夹中并打开
image.setImageURI("file:///android_asset/" + nameFromDB);
回答by Mudasar
String path = "sdcard/camera_app/name.jpg"; img.setImageDrawable(Drawable.createFromPath(path));
String path = "sdcard/camera_app/name.jpg"; img.setImageDrawable(Drawable.createFromPath(path));