本文介绍了如何从 url 为 imageView 设置图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 ImageView 中使用 Url 设置图像,例如我有这个 url
I wanna set Image in ImageView using Url for example I have this url
但是没有设置url的选项
but there is no option to set url
推荐答案
创建一个扩展 AsyncTask
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
并像这样调用它 new ImageLoadTask(url, imageView).execute();
直接方法:
使用此方法并将您的网址作为字符串传递.它返回一个位图.将位图设置为您的 ImageView.
Use this method and pass your url as string. It returns a bitmap. Set the bitmap to your ImageView.
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
然后这样到 ImageView:
And then this to ImageView like so:
imageView.setImageBitmap(getBitmapFromURL(url));
不要忘记 maifest 中的这个权限.
And dont forget about this permission in maifest.
<uses-permission android:name="android.permission.INTERNET" />
注意:
尝试从另一个线程或 AsyncTask 调用此方法,因为我们正在执行网络操作.
Try to call this method from another thread or AsyncTask because we are performing networking operations.
这篇关于如何从 url 为 imageView 设置图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!