Glide加载图片时通常会设置占位图。
1.Glide加载图片到imageview设置占位图
val options = RequestOptions()
.placeholder(R.drawable.tlive_main_img_poster_default)//图片加载出来前,显示的图片
.fallback( R.drawable.tlive_main_img_poster_default) //url为空的时候,显示的图片
.error(R.drawable.tlive_main_img_poster_default);//图片加载失败后,显示的图片
Glide.with(this).load("http://zp-o.img.leiniao.com/live/d75a11e7-d2d4-4880-83b3-c358423f1393x.png").apply(options).into(imageposter)
加载图片到imageview的直接使用RequestOptions即可
2.Glide以bitmap形式加载图片设置占位图
fun loadImageIntoBackground(
view: View,
context: Context,
url: String,
corner: Int,
placeHolder: Int,
width: Int,
height: Int,
imageLoaderDrawableListener: ImageLoaderDrawableListener
) {
val option: RequestOptions = RequestOptions().override(width, height)
.transform(RoundedCorners(corner))
.placeholder(placeHolder)
.error(placeHolder)
.fallback(placeHolder)
Glide.with(context).asBitmap().load(url).apply(option).into(
object : CustomViewTarget<View, Bitmap>(view) {
override fun onLoadFailed(errorDrawable: Drawable?) {
LogUtils.d("ImageLoadUtils", "onLoadFailed${errorDrawable}")
imageLoaderDrawableListener.onLoadFail(errorDrawable)
}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
if (resource != null && !resource.isRecycled) {
imageLoaderDrawableListener.onLoadImageSuccess(
url,
BitmapDrawable(context.resources, resource)
)
}
}
override fun onResourceLoading(placeholder: Drawable?) {
LogUtils.d("ImageLoadUtils", "onResourceLoading${placeholder}")
super.onResourceLoading(placeholder)
view.background = placeholder
}
override fun onResourceCleared(placeholder: Drawable?) {
}
}
)
}
使用CustomViewTarget方式加载图片需要在onResourceLoading回调中设置占位图,onLoadFailed中设置加载错误的图片