我是怎么做事的。更短的方式,更简洁的代码
例子:
progress_bar.visibility = View.VISIBLE
profilePicturePath?.let {
GlideApp.with(applicationContext)
.load(CloudStorage.pathToReference(it))
.placeholder(R.drawable.placeholder)
.listener(GlideImpl.OnCompleted {
progress_bar.visibility = View.GONE
})
.into(profile_picture)
} ?: profile_picture.setImageResource(R.drawable.placeholder)
用法:
GlideImpl.OnCompleted {
// completed
}
只是传递GlideImpl.OnCompleted { }
给 Glide 的.listener()
接受 Glide 的 RequestListener 的 GlideImpl.kt 类
import android.graphics.drawable.Drawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
object GlideImpl {
object OnCompleted : RequestListener<Drawable> {
private lateinit var onComplete: () -> Unit
operator fun invoke(onComplete: () -> Unit): OnCompleted {
OnCompleted.onComplete = { onComplete() }
return this
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
onComplete()
return false
}
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
onComplete()
return false
}
}
}
就是这样!