目录:
2,Glide4-入门教程-2-占位符的使(placeholder, error, fallback)
一、简介
这一节主要是讲,Glide4中占位图的使用方法,包括(placeholder, error,fallback)三种占位图
二、占位符定义和类型
1,定义:
占位符是当请求正在执行时被展示的 Drawable 。当请求成功完成时,占位符会被请求到的资源替换。如果被请求的资源是从内存中加载出来的,那么占位符可能根本不会被显示。
2,类型:
1)placeholder // 正在请求图片的时候展示的图片
2)error // 如果请求失败的时候展示的图片 (如果没有设置,还是展示placeholder的占位符)
3)fallback // 如果请求的url/model为 null 的时候展示的图片 (如果没有设置,还是展示placeholder的占位符)
三、用法
有两种方法设置,一是RequestOptios中设置(重点介绍),二是利用GlideApp直接展示。如下面的实例
1,placeholder
占位符是当请求正在执行时被展示的 Drawable 。当请求成功完成时,占位符会被请求到的资源替换。如果被请求的资源是从内存中加载出来的,那么占位符可能根本不会被显示。如果请求失败并且没有设置 error Drawable ,则占位符将被持续展示。类似地,如果请求的url/model为 null ,并且 error Drawable 和 fallback 都没有设置,那么占位符也会继续显示。
在RequestOption设置
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String imageUrl = "https://www.niwoxuexi.com/statics/images/nougat_bg.png";
ImageView imageView = findViewById(R.id.image_view);
RequestOptions options = new RequestOptions()
.placeholder(R.drawable.ic_launcher)
// .placeholder(new ColorDrawable(Color.BLACK)) // 或者可以直接使用ColorDrawable
;
Glide.with(this)
.load(imageUrl)
.apply(options)
.into(imageView);
}
或者 GlideApp (下面两种就不介绍GlideApp方式了)
GlideApp.with(this)
.load(url)
.placeholder(R.drawable.ic_launcher)
//.placeholder(new ColorDrawable(Color.BLACK)) // 或者可以直接使用ColorDrawable
.into(view);
2,error
error Drawable 在请求永久性失败时展示。error Drawable 同样也在请求的url/model为 null ,且并没有设置 fallback Drawable 时展示。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String imageUrl = "https://www.niwoxuexi.com/statics/images/nougat_bg.png";
ImageView imageView = findViewById(R.id.image_view);
RequestOptions options = new RequestOptions()
// .error(new ColorDrawable(Color.BLUE)) // 用ColorDrawable或者下面的资源文件
.error(R.drawable.ic_error);
Glide.with(this)
.load(imageUrl)
.apply(options)
.into(imageView);
}
3, fallback
fallback Drawable 在请求的url/model为 null 时展示。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String imageUrl = "https://www.niwoxuexi.com/statics/images/nougat_bg.png";
ImageView imageView = findViewById(R.id.image_view);
RequestOptions options = new RequestOptions()
// .fallback(new ColorDrawable(Color.BLUE)) // 用ColorDrawable或者下面的资源文件
.fallback(R.drawable.ic_fallback);
Glide.with(this)
.load(imageUrl)
.apply(options)
.into(imageView);
}
4,最后来段三种占位符同时用的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String imageUrl = "https://www.niwoxuexi.com/statics/images/nougat_bg.png";
ImageView imageView = findViewById(R.id.image_view);
RequestOptions options = new RequestOptions()
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_error)
.fallback(R.drawable.ic_fallback);
Glide.with(this)
.load(imageUrl)
.apply(options)
.into(imageView);
}