问题描述
我有一个来自我的 rest API 的图像 url.现在我想在加载活动时将其设置为图像视图.下面是我如何从 rest 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 对象来获取该图像 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();
}
我使用上述代码将图像加载到图像视图对象,即 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 库:编译'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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!