Skip to content

Instantly share code, notes, and snippets.

@rinav
Created June 26, 2019 14:24
Show Gist options
  • Select an option

  • Save rinav/ff2ffdd09ac34f102852a07ae129152c to your computer and use it in GitHub Desktop.

Select an option

Save rinav/ff2ffdd09ac34f102852a07ae129152c to your computer and use it in GitHub Desktop.
Glide issue when both width and height are unknown
/*
* How to effectively use Glide to load Images in both RecyclerView and normal ImageView in layout, when we do not know the image size before hand.
* My ImageViews are both wrap-content, also my REST api does not provide size values in responses.
* Moreover I have many different image sizes in views.
*/
... // Somewhere in my Adapter
internal var isImageSizeFound = false
inner class ShowsListViewHolder internal constructor(itemView: View) :
RecyclerView.ViewHolder(itemView), View.OnClickListener {
internal val showImage: SquareImageView = itemView.item_show_image
// other views
internal var width: Int = 0
internal var height: Int = 0
init {
if (!isImageSizeFound) {
itemView.viewTreeObserver
.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
//don't forget remove this listener
itemView.viewTreeObserver.removeOnGlobalLayoutListener(this)
width = showImage.width
height = showImage.height
if (width > 1 || height > 1) {
isImageSizeFound = true
}
logConsole("onBindViewHolder: widthHeight: ($width, $height)")
}
})
}
}
override fun onClick(view: View) {
listener.onRowClicked(adapterPosition)
// view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
fun getImageWidth(): Int {
return if(width == 0) 200 else width
}
fun getImageHeight(): Int {
return if(height == 0) 200 else height
}
}
// and then in OnBindViewHolder
override fun onBindViewHolder(holder: ShowsListViewHolder, position: Int) {
holder.showImage.loadImage(album.image, width = holder.getImageWidth(), height = holder.getImageHeight())
// ...
}
// My Extension function to load image from url using Glide
fun ImageView.loadImage(urlOrResource: Any,
width: Int,
height: Int,
@DrawableRes placeholder: Int = R.drawable.placeholder,
@DrawableRes error: Int = R.drawable.error) {
GlideApp.with(context)
.load(urlOrResource)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.apply {
RequestOptions().override(width, height)
}
.thumbnail(0.25F)
.error(context.drawable(error))
.into(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment