您的位置:首页 > 理论基础 > 计算机网络

android:怎么在Listview里面加载网络图片?或者在背景中加载网络图片?类似评论列表的头像等

2017-11-01 10:13 567 查看
在很多的情况下,我们不得不从网上加载图片到自己的本机上。如你可能会用到评论或点赞类似的列表,需要加载网上的头像到listview中。面对这个问题,我找了一个相对简单地方法去解决这个问题,包括配置文件在内一共用不了几行代码。

这里有请我们的第三方库Glide,该库是Google推荐的,这库也确实好用,它不单可以实现加载静态图片,还可加载动图,而且在Activity和Fragment中都能使用 。一库学会,啥图不怕。

加载库

第一个加载Glide库,第二个是Glide的依赖库

在build.gradle文件下添加:

dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:appcompat-v7:24.2.1'
}


调用

调用Glide核心类:下面一句话就已经可以加载图片了

Glide.with(context)
.load(URL)
.into(imgID);


解释:context:很多android类都会用contenxt,和别处用法一致。

URL:图片的URL,例如我的csdn头像:http://avatar.csdn.net/9/E/8/1_zhangwenchaochao.jpg

imgID:位置view,就是imgID = (imgview) finviewbyiId(R.ID.xxx);

例子

测试的时候发现我的头像的URL经常请求不到,我使用百度了百度的图片,随便找一张图片的url就可以使用。

效果如下



主活动Java代码

调用Glide核心类:下面一句话就已经可以加载图片了

public class MainActivity extends AppCompatActivity {

private ImageView imgTest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgTest = (ImageView) findViewById(R.id.img_test);

String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";

Glide.with(this)         //主要这一句
.load(url)
.into(imgTest);
}
}


主活动XML代码

调用Glide核心类:下面一句话就已经可以加载图片了

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.glidetest1.MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Glide Test" />

<ImageView
android:id="@+id/img_test"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


cadn下载地址:http://download.csdn.net/download/zhangwenchaochao/10048772

加载到listview和加载到这里用法一样,下一篇博客会讲到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Glide