Android:如何以编程方式从URL设置图像到imageview

Ter*_*nce 5 url android image bitmap imageview

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

Message message=new Message();
String imageUrl=message.getImageUrl();
Run Code Online (Sandbox Code Playgroud)

我从我的数据库中获取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();
}
Run Code Online (Sandbox Code Playgroud)

我使用上面的代码将图像加载到imageview对象contentImageView.

但我仍然无法将此图像加载到imageview,没有任何东西被加载.

有什么想法吗?

Moh*_*rei 10

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

Picasso.with(getContext()).load(imgUrl).fit().into(contentImageView);
Run Code Online (Sandbox Code Playgroud)

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