Skip to content

Instantly share code, notes, and snippets.

@yushman
Last active Nov 9, 2019
Embed
What would you like to do?
Adding listener to RecyclerView Items & Views
// !!!
// If you need to handle clicking on the entire element only, you can omit adding View to listener lambda - listener(myModel)
// so in "bind" method you can write only - view.setOnclickListener { listener.invoke(myViewModel) }
class MyAdapter (private val listener: (MyModel, View) -> Unit): RecyclerView.Adapter<MyAdapter.MyViewHolder>{
val myItemList = listOf<MyModel>()
//...
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(myItemList[position], listener) //bind listener to position
}
//...
inner class MyViewHolder(view: View): RecyclerView.ViewHolder(view) {
val btnOne = view.findViewById<Button>(R.id.some_button)
val someView = view.findViewById<View>(R.id.some_view)
//...
fun bind(myModel: MyModel, listener: (MyModel, View) -> Unit){
btnOne.setOnClickListener { listener.invoke(myModel, btnOne) }
someView.setOnClickListener { listener.invoke(myModel, someView) }
// if you need to handle clicking on the entire element only
// view.setOnClickListener { listener.invoke(myModel) }
//...
}
}
}
// Usage in Activity or Fragment
// In onCreate or near RV initialization
val adapter = MyAdapter { doSomeLogic ( myModel, view ) }
fun doSomeLogic (myModel, view){
when(view.id){
R.id.some_button -> doButtonLogic(myModel) // need to implement
R.id.some_view -> doViewLogic(myModel) // need to implement
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment