In case anyone is looking for a more no-frills answer, I tried the following - which is very similar to the solution from AfzalivE:
In my Adapter class I passed the clickListener
as a parameter. On onBindViewHolder
, I've used setOnClickListener
to call clickListener
and handle click event.
MyAdapter.kt:
class MyAdapter constructor(objects: ArrayList<MyObject>, val clickListener: (MyObject) -> Unit) : RecyclerView.Adapter<MyAdapter.Holder>() {
private var mObjects : ArrayList<MyObject> = ArrayList<MyObject>()
init {
mObjects = objects
}
override fun onBindViewHolder(holder: Holder?, position: Int) {
var item : MyObject = objects[position]
// Calling the clickListener sent by the constructor
holder?.containerView?.setOnClickListener { clickListener(item) }
}
// More code (ViewHolder definitions and stuff)...
}
Note: I needed a reference from my list item's container (the root view), which in this case is containerView
Then I passed my object as parameter without need for searching it on a list again and handle it directly on my Activity
class, in the moment I set the adapter:
MyActivity.kt:
myRecyclerView?.adapter = MyAdapter(mObjects) {
Log.e("Activity", "Clicked on item ${it.itemName}")
}
Update
If you need to get the position of the clicked item, just define it as parameter on the callback and then send it back later. Notice the val clickListener: (MyObject, Int) -> Unit
below:
MyAdapter.kt
class MyAdapter constructor(objects: ArrayList<MyObject>, val clickListener: (MyObject, Int) -> Unit) : RecyclerView.Adapter<MyAdapter.Holder>() {
// Rest of the code...
Then on onBindViewHolder()
you pass the position when calling the callback method:
override fun onBindViewHolder(holder: Holder?, position: Int) {
var item : MyObject = objects[position]
// Calling the clickListener sent by the constructor
holder?.containerView?.setOnClickListener { clickListener(item, position) }
}
And on MyActivity.kt, you'll have to change the way you set the adapter so you can get the position. Like this:
myRecyclerView?.adapter = MyAdapter(mObjects) { itemDto: MyObject, position: Int ->
Log.e("MyActivity", "Clicked on item ${itemDto.someItemPropertyLikeName} at position $position")
}