在 Android 中的 ImageView 中加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3193356/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:05:54  来源:igfitidea点击:

Load Images in ImageView in Android

androidandroid-widgetimageview

提问by Paresh Mayani

In my application....there are some images like temp1.jpg, temp2.jpg .....upto temp35.jpg,

在我的应用程序中......有一些图像,如 temp1.jpg、temp2.​​jpg .....upto temp35.jpg,

so on button clicking, i want to load one-by-one image in ImageView .... i want to do like:

所以在单击按钮时,我想在 ImageView 中加载一张一张的图像......我想做:

cnt=1;
imagename="temp" + cnt + ".jpg";
cnt++;

cnt=1;
imagename="temp" + cnt + ".jpg";
cnt++;

so my confusion is that "is there anyway to load an image in imageview from string(imagename variable) like temp1.jpg,etc."

所以我的困惑是“无论如何都可以从字符串(图像名称变量)(如 temp1.jpg 等)加载图像视图中的图像。”

采纳答案by Paresh Mayani

I implemented below solution and it's working for me:

我实现了以下解决方案,它对我有用:

while(cnt!=n)
{
 String icon="temp" + cnt;
 int resID =
 getResources().getIdentifier(icon,"drawable","testing.Image_Demo");
 imageView.setImageResource(resID);
 cnt++; 
}

回答by xil3

You could try this:

你可以试试这个:

int cnt = 1;
//Bitmap bitmap = BitmapFactory.decodeFile("temp" + cnt + ".jpg");
int imageResource = getResources().getIdentifier("drawable/temp" + cnt + ".jpg", null, getPackageName());
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageResource);
imageView.setImageBitmap(bitmap);
cnt++;

Hope that's what you were looking for.

希望这就是你要找的。

回答by slup

Why not something like

为什么不像

File f = new File(PathToFiles + "/temp" + cnt + ".jpg");
if (f.exists()) {
  Drawable d = Drawable.createFromPath(f);
  imageview.setImageDrawable(d);
}

回答by Itsik

I don't know if this is the best solution but you can make a Hashtable that maps the image names to the resources.

我不知道这是否是最好的解决方案,但您可以制作一个将图像名称映射到资源的哈希表。

Hashtable map;
map.put("temp1", R.drawable.temp1) // assuming temp1.jpg is in /drawable

and then you could load the ImageView from a drawable.

然后你可以从一个drawable加载ImageView。

 String imageName = "temp" + n;
 Drawable d = getResources().getDrawable((int)map[imageName]);
 ImageView i = new ImageView(this);
 i.setImageResource(d);