Last active
April 20, 2023 10:14
-
-
Save arcadefire/1e3a95314fdbdd78fb211b099d6ec9da to your computer and use it in GitHub Desktop.
Add addOnItemClickListener easily to a RecyclerView using Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}) |
Thanks, you saved me
Thanks, Saved my day
But how to identify child view instead on itemView.
Thank you ♥.
Thank you , Save my day
This is very helpful. Thank you.
Well, That's pretty straight forward and short. Nice work man, 👍
Great! I just needed to remove the null exceptions(?) and it works great. Thank you!!
Great! I just needed to remove the null exceptions(?) and it works great. Thank you!!
It helped me too! Thanks to the author!!!
thanks
Thanks man... you save my day
Thanks a lot!!!
Thank you!!
perfect, thanks a lot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just awesome! Thank you