How do you add click listener to a view in a ViewHolder?
You would do like this in kotlin:
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.setOnClickListener {
( your on click logic)
}
}
Yes, exactly. Thanks @ayonymus :)
If you want a click listener on the root view of every Item in your adapter, Groupie can do that for you by calling GroupAdapter.setOnClickListener().
If I want a click listener that I set myself (usually on some part of an item and not the whole view), I usually create a meaningful interface, and pass it in the item's constructor. e.g.:
class ProductItem(val product: Product, val heartListener: OnHeartClickedListener) {
interface OnHeartClickedListener {
fun onHeartClicked(item: Item, product: Product)
}
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.heart.setOnClickListener {
heartListener.onHeartClicked(this@ProductItem, product)
}
}
}
You would do like this in kotlin:
override fun bind(viewHolder: ViewHolder, position: Int) { viewHolder.itemView.setOnClickListener { ( your on click logic) } }
That is not really a efficient way to execute, We should be not be recycling OnClickListener. Instead, pass a single listener object into the ViewHolder, and it should return with adapterPosition to the adapter. Currently, we have to override createViewHolder to make it really efficient.
The problem is still relevant. I am getting data from the backend and I have to add listeners to the items in a loop.
I solved this issue like so:
class ProductItem(val product: Product, val heartListener: OnHeartClickedListener) {
interface OnHeartClickedListener {
fun onHeartClicked(item: Item, product: Product)
}
private val onClickListener = OnClickListener {
heartListener.onHeartClicked(this@ProductItem, product)
}
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.heart.setOnClickListener(onClickListener)
}
}
Most helpful comment
Yes, exactly. Thanks @ayonymus :)
If you want a click listener on the root view of every Item in your adapter, Groupie can do that for you by calling
GroupAdapter.setOnClickListener().If I want a click listener that I set myself (usually on some part of an item and not the whole view), I usually create a meaningful interface, and pass it in the item's constructor. e.g.: