For every 21st item in my recyclerview I would like to make the image in that view larger. Should be simple enough.
I add this code to the onBindViewHolder of my ItemAdapter class:
override fun onBindViewHolder(holder: ItemViewHolder, pos: Int) {
val currentItem = getItem(pos)
val largeItemView = pos >= 21 && pos % 21 == 0
Log.e("ItemAdapter", "Position: $pos, largeItemView bool: $largeItemView")
if (currentItem != null) {
holder.bind(currentItem, pos, largeItemView)
}
}
The largeItemView boolean val gets passed to my ItemViewHolder
class ItemViewHolder(private val binding: ShopProductItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: RoomItem, pos: Int, largeItemView: Boolean) {
var imageBefore = item.product_image_list?.substringBefore(',')
imageBefore = addHttpsToImageUrl(imageBefore)
if (largeItemView) {
// This is getting called when largeItemView is false??
binding.apply {
imageViewItem.layoutParams.height = 800
imageViewItem.scaleType = ImageView.ScaleType.FIT_XY
Glide.with(itemView)
.load(imageBefore)
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageViewItem)
imageViewItem.setOnClickListener {
logProductInfo(item, pos, imageBefore, largeItemView)
}
}
} else {
binding.apply {
Glide.with(itemView)
.load(imageBefore)
.centerCrop()
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageViewItem)
imageViewItem.setOnClickListener {
logProductInfo(item, pos, imageBefore, largeItemView)
}
}
}
}
Every 21st item in the recyclerview does increase in height. Which is great. However other items in the recyclerview randomly also have a height increase. I cannot explain this. I have set up logs to display the position and boolean of the item I click. I will click on a large image item that should not be large, and the log says that the largeItemView boolean is false. So how could the code that increases the size of the image have been reached?
Here are some screenshots of the log output in case it helps.
This problem is baffling me. Any ideas on what's going on here?
CodePudding user response:
Thanks to Pawel, I have the solution
"Viewholders are reused - your else case must restore height and scaleType to default to account for case where viewholder you're binding was bound to position that triggered "largeItemView" before"
I added
imageViewItem.layoutParams.height = 600
imageViewItem.scaleType = ImageView.ScaleType.CENTER_CROP
to the else block in my itemviewholder and it has fixed the issue.