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.
You can put the Function where you want, but it should be accessible from "Adapter.onBindViewHolder()" method.
If you place your "onClick()" lambda INSIDE the Adapter Class then it will be difficult to interact (if needed) with something OUTSIDE this Adapter. Infact it's common pratice to mark extended Adapter Class (your "MetarItemAdapter") as STATIC due to better performance and less memory consumption. If the Class is Static you will not "touch" nothing outside the Adapter because UserInterface is usually instantiated in one Object (an Activity, a Fragment, etc...), but if you pass the Function as an argument it could be created from everywhere.