安卓 : How to set an image to an imageview from a url programatically

标签 android image url bitmap imageview

我有一个来 self 的 rest API 的图片 url。现在我想在加载 Activity 时将其设置为 ImageView 。下面是我如何从 rest api 获取 bean,然后从中获取 URL。

Message message=new Message();
String imageUrl=message.getImageUrl();

我从我的数据库中获取 Message 对象,图像 url 包含在该 Message 对象中。

然后我使用 Url 对象获取该图像 url。

URL url = null;
try {
     url = new URL(imageUrl);
     Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
     contentImageView.setImageBitmap(bmp);
} catch (Exception e) {
     e.printStackTrace();
}

我使用上面的代码将图像加载到 ImageView 对象,该对象是 contentImageView

但我仍然无法将此图像加载到 imageview,没有加载任何内容。

有什么想法吗?

最佳答案

最简单的方法是使用 Picasso 或 Glide 之类的工具:

Picasso.with(getContext()).load(imgUrl).fit().into(contentImageView);

您可以在您的 gradle 中添加 picasso 库: 编译 'com.squareup.picasso:picasso:2.5.2'

关于安卓 : How to set an image to an imageview from a url programatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43971819/

相关文章:

android webview客户端 Activity 指示器

android - 扩展 View 类和使用布局 xml 文件的示例代码

wpf - 如何在 xamarin.froms 中为 WPF 中的图像添加鼠标事件的缩放功能

java - URL.openconnection() 时做了什么?

javascript - 使用 JQuery 检查 url 是否包含字符串

android python 脚本 : GUI?

android - 禁用弹出键盘android-studio

c# - WPF 是否讨厌猫图像?或 : Why can I reference one, 但不是来自同一文件夹的其他图像?

php - 你如何处理PHP中的临时图片上传?

javascript - 使用 Javascript 进行(多次)重定向后获取最终 URL