Skip to content

Instantly share code, notes, and snippets.

@arcadefire
Last active April 20, 2023 10:14
  • Star 33 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save arcadefire/1e3a95314fdbdd78fb211b099d6ec9da to your computer and use it in GitHub Desktop.
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

Just awesome! Thank you

@samuelhoug
Copy link

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

Thank you ♥.

@fvmzr
Copy link

fvmzr commented Jun 22, 2019

Thank you , Save my day

@varadmondkar
Copy link

This is very helpful. Thank you.

@Puneet1796
Copy link

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

@yushman
Copy link

yushman commented Oct 22, 2019

@kiviabrito
Copy link

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

@OwloneDev
Copy link

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

thanks

@ardiansah21
Copy link

Thanks man... you save my day

@nishchaljs
Copy link

Thanks a lot!!!

@yancorrea1995
Copy link

Thank you!!

@ramdaramda
Copy link

perfect, thanks a lot

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