1.库的引入:
dependencies { compile 'com.github.bumptech.glide:glide:3.5.2' compile 'com.android.support:support-v4:22.0.0' }
2.Glide加载网络图片需要添加网络权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
3.基本方法使用
Glide.with(this)
//加载网址
.load(picUrl) //设置占位图 .placeholder(R.mipmap.ic_launcher) //加载错误图 .error(R.mipmap.ic_launcher) //磁盘缓存的处理 .diskCacheStrategy(DiskCacheStrategy.ALL) .into(ivShow);
4.加载Gif图片
Glide.with(MainActivity.this) .load(picGifUrl) .asGif() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(ivShow);
5.实例代码
xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/iv_img" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_loadImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Glide加载图片" /> <Button android:id="@+id/btn_loadImageGif" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Glide加载Gif图片" /> </LinearLayout>
MainActivity.java
package zm.ztd.com.paydemo; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private final String picUrl="http://4493bz.1985t.com/uploads/allimg/150127/4-15012G52133.jpg"; private final String picGifUrl="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=699931848,3785826281&fm=116&gp=0.jpg"; private ImageView ivShow; private Button btnLoadImag,btnLoadGif; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { ivShow= (ImageView) findViewById(R.id.iv_img); btnLoadImag= (Button) findViewById(R.id.btn_loadImage); btnLoadImag.setOnClickListener(this); btnLoadGif= (Button) findViewById(R.id.btn_loadImageGif); btnLoadGif.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_loadImage: loadImage(); break; case R.id.btn_loadImageGif: loadGifImag(); break; } } private void loadImage(){ Glide.with(this) .load(picUrl) //设置占位图 .placeholder(R.mipmap.ic_launcher) //加载错误图 .error(R.mipmap.ic_launcher) //磁盘缓存的处理 .diskCacheStrategy(DiskCacheStrategy.ALL) .into(ivShow); } private void loadGifImag(){ Glide.with(MainActivity.this) .load(picGifUrl) .asGif() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(ivShow); } }