This is a question to aid understanding. I have a recyclerview and after a lot of effort I was finally able to handle clicking an item in the recyclerview. It was difficult because I do not see the logic behind how it is done. Here are some code snippits:
In MainActivity, inititialising the adapter:
// Adapter takes a lambda function as a parameter - this will go through to what happens onClick
val adapter = MetarItemAdapter{
a: String -> u.l(this, a)
}
In adapter class, the class initialisation with the required lambda function, now named onClick:
class MetarItemAdapter(
private val onClick: (String) -> Unit
) : RecyclerView.Adapter<MetarItemAdapter.MetarViewHolder>() {
...rest of adapter code
Within onBindViewHolder, here is how I have used onClick:
override fun onBindViewHolder(holder: MetarViewHolder, position: Int) {
val currentItem = metarList[position]
holder.tvMetar.text = currentItem.metar
holder.tvMetar.setOnClickListener {
onClick(holder.tvMetar.text.toString())
}
}
After looking at lots of stack overflow questions, I gather that this is the way to handle a click in a recyclerview.
My question is why we have to define a function all the way back in main activity, for it to be required to initialise the class, for it to be available throughout the class, for it just to be used for simple click handling in onBindViewHolder? Why can the code to handle a click not just be contained within onBindViewHolder?
Thank you for reading, I hope it makes sense. Happy to clarify any points.