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 | |
} | |
}) |
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
Great! I just needed to remove the null exceptions(?) and it works great. Thank you!!