Im trying to create an app with a recyclerview, and I am trying to figure out the following code from an android example. Like what is the onClick value they are putting in the first class, and what is the lambda expression for and what does it do? I notice a similar lambda is in the class below it as well. If anyone can please explain the code. Thank you.
class FlowersAdapter(private val onClick: (Flower) -> Unit) :
ListAdapter<Flower, FlowersAdapter.FlowerViewHolder>(FlowerDiffCallback) {
/* ViewHolder for Flower, takes in the inflated view and the onClick behavior. */
class FlowerViewHolder(itemView: View, val onClick: (Flower) -> Unit) :
RecyclerView.ViewHolder(itemView) {
private val flowerTextView: TextView = itemView.findViewById(R.id.flower_text)
private val flowerImageView: ImageView = itemView.findViewById(R.id.flower_image)
private var currentFlower: Flower? = null
init {
itemView.setOnClickListener {
currentFlower?.let {
onClick(it)
}
}
}
/* Bind flower name and image. */
fun bind(flower: Flower) {
currentFlower = flower
flowerTextView.text = flower.name
if (flower.image != null) {
flowerImageView.setImageResource(flower.image)
} else {
flowerImageView.setImageResource(R.drawable.rose)
}
}
}
CodePudding user response:
The onClick
parameter has a type of (Flower) -> Unit
. That represents a function, which takes a single Flower
parameter (in the parentheses) and returns Unit
(i.e. "doesn't return anything").
That means that onClick
is a function, and you can call it like onClick(someFlower)
, which is what's happening in that click listener set up in the init
block. The naming might make it a little confusing, but it's basically this:
- pass in some handler function
- set up a click listener on
itemView
- when
itemView
is clicked, call the handler function, passingcurrentFlower
so it's just a way for you to provide some behaviour to handle a flower being clicked. You still need the click listener - that's a thing that operates on a View
and handles click interactions. But inside that listener, you can do what you like when the click is detected, and in this case it's running some externally provided function