Android:如何以编程方式从URL设置图像到imageview [英] Android : How to set an image to an imageview from a url programatically

查看:1678
本文介绍了Android:如何以编程方式从URL设置图像到imageview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自我的其他API的图片网址。现在我想在加载活动时将其设置为imageview。下面是我如何从其余的api获取bean,然后从中获取URL。

I have an image url coming from my rest API. Now I want to set it to an imageview when activity is loading. Below is how I get the bean from the rest api and then get the URL out of it.

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

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

I get Message object from my database and image url is include in that Message object.

然后我使用Url对象获取该图片网址。

Then I used Url object to get that image url.

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

我使用上面的代码将图像加载到<$ c的imageview对象$ c> contentImageView 。

I used above codes to load image to an imageview object which is contentImageView.

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

But still I cannot load this image to imageview, Nothing is getting loaded.

有任何想法吗?

推荐答案

最简单的方法是使用像Picasso或Glide这样的东西:

The easiest way to do it is by using something like Picasso or Glide:

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

你可以在你的gradle中添加picasso库:
compile' com.squareup.picasso:picasso:2.5.2'

you can add picasso library in your gradle: compile 'com.squareup.picasso:picasso:2.5.2'

这篇关于Android:如何以编程方式从URL设置图像到imageview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆