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

This comment has been minimized.

Copy link

@RonnyKibet1 RonnyKibet1 commented Oct 29, 2018

Just awesome! Thank you

@samuelhoug

This comment has been minimized.

Copy link

@samuelhoug samuelhoug commented Nov 9, 2018

Thanks, you saved me

@kashyapasrc

This comment has been minimized.

Copy link

@kashyapasrc kashyapasrc commented Jan 8, 2019

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

@majedalmoqbeli

This comment has been minimized.

Copy link

@majedalmoqbeli majedalmoqbeli commented Apr 3, 2019

Thank you .

@forooghVarmazyar

This comment has been minimized.

Copy link

@forooghVarmazyar forooghVarmazyar commented Jun 22, 2019

Thank you , Save my day

@varadmondkar

This comment has been minimized.

Copy link

@varadmondkar varadmondkar commented Jul 24, 2019

This is very helpful. Thank you.

@Puneet1796

This comment has been minimized.

Copy link

@Puneet1796 Puneet1796 commented Sep 20, 2019

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

@yushman

This comment has been minimized.

@kiviabrito

This comment has been minimized.

Copy link

@kiviabrito kiviabrito commented Jan 7, 2020

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

@OwloneDev

This comment has been minimized.

Copy link

@OwloneDev 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

This comment has been minimized.

Copy link

@Real-young-man Real-young-man commented Aug 31, 2020

thanks

@ardiansah21

This comment has been minimized.

Copy link

@ardiansah21 ardiansah21 commented Oct 3, 2020

Thanks man... you save my day

@nishchaljs

This comment has been minimized.

Copy link

@nishchaljs nishchaljs commented Nov 12, 2020

Thanks a lot!!!

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