Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add addOnItemClickListener easily to a RecyclerView using Kotlin
import android.support.v7.widget.RecyclerView
import android.view.View
interface OnItemClickListener {
fun onItemClicked(position: Int, view: View)
}
fun RecyclerView.addOnItemClickListener(onClickListener: OnItemClickListener) {
this.addOnChildAttachStateChangeListener(object: RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewDetachedFromWindow(view: View?) {
view?.setOnClickListener(null)
}
override fun onChildViewAttachedToWindow(view: View?) {
view?.setOnClickListener({
val holder = getChildViewHolder(view)
onClickListener.onItemClicked(holder.adapterPosition, view)
})
}
})
}
// Usage:
recyclerView.addOnItemClickListener(object: OnItemClickListener {
override fun onItemClicked(position: Int, view: View) {
// Your logic
}
})
@RonnyKibet1
Copy link

RonnyKibet1 commented Oct 29, 2018

Just awesome! Thank you

@samuelhoug
Copy link

samuelhoug commented Nov 9, 2018

Thanks, you saved me

@kashyapasrc
Copy link

kashyapasrc commented Jan 8, 2019

Thanks, Saved my day
But how to identify child view instead on itemView.

@majedalmoqbeli
Copy link

majedalmoqbeli commented Apr 3, 2019

Thank you .

@fvmzr
Copy link

fvmzr commented Jun 22, 2019

Thank you , Save my day

@varadmondkar
Copy link

varadmondkar commented Jul 24, 2019

This is very helpful. Thank you.

@Puneet1796
Copy link

Puneet1796 commented Sep 20, 2019

Well, That's pretty straight forward and short. Nice work man, 👍

@yushman
Copy link

yushman commented Oct 22, 2019

@kiviabrito
Copy link

kiviabrito commented Jan 7, 2020

Great! I just needed to remove the null exceptions(?) and it works great. Thank you!!

@OwloneDev
Copy link

OwloneDev commented Aug 10, 2020

Great! I just needed to remove the null exceptions(?) and it works great. Thank you!!

It helped me too! Thanks to the author!!!

@Real-young-man
Copy link

Real-young-man commented Aug 31, 2020

thanks

@ardiansah21
Copy link

ardiansah21 commented Oct 3, 2020

Thanks man... you save my day

@nishchaljs
Copy link

nishchaljs commented Nov 12, 2020

Thanks a lot!!!

@yancorrea1995
Copy link

yancorrea1995 commented Apr 1, 2022

Thank you!!

@ramdaramda
Copy link

ramdaramda commented Jun 11, 2022

perfect, thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment