Skip to content

Instantly share code, notes, and snippets.

@sajjadjaved01
Created August 28, 2019 14:24
Show Gist options
  • Save sajjadjaved01/5420e4d241c0d9f9569c3ee864c677ef to your computer and use it in GitHub Desktop.
Save sajjadjaved01/5420e4d241c0d9f9569c3ee864c677ef to your computer and use it in GitHub Desktop.
DataBinding with ImageView & Glide
//Remember: The method needs to be public static and the first parameter will be the view. This is very important.
// this is for just for single loading.
companion object {
@JvmStatic
@BindingAdapter("profileImage")
fun loadImage(view: ImageView, profileImage: String) {
Glide.with(view.context)
.load(profileImage)
.into(view)
}
}
// Usage in XML
app:profileImage="@{user.profileImage}"
// Databinding ImageView with Placeholder Glide
// Note that we’ve set requireAll to false. This ensures that this adapter is used even if one of the attributes is not set in xml.
// Omit this if you want to ensure this gets called only if all attributes are provided.
companion object {
@JvmStatic
@BindingAdapter(value = ["profileImage", "error"], requireAll = false)
fun loadImage(view: ImageView, profileImage: String, error: Int) {
Glide.with(view.context)
.load(profileImage)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
view.setImageResource(error)
return true
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
view.setImageDrawable(resource)
return true
}
})
.into(view)
}
}
// Now in our imageView layout, we can provide a resource for the error state.
app:error="@{user.errorImage}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment