This article is the third in a series of introduction to RecyclerView. If you already have some knowledge of creating RecyclerView, read on. If you are not already familiar with it, I suggest you read the first article in this series.

When using RecyclerView to display list data, you may need to respond to click events for list elements. This response processing includes: opening a page with more data, displaying a toast, deleting an element, and so on. There are numerous related response events, but they all need to be implemented via onClick().

Defining click actions

Before creating a listener, add a function to the Activity class that handles the response after a click.

<! -- Copyright2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

private fun adapterOnClick(flower: Flower) {
   val intent = Intent(this, FlowerDetailActivity()::class.java)
   intent.putExtra(FLOWER_ID, flower.id)
   this.startActivity(intent)
}
Copy the code

Next, modify the Adapter constructor to pass in the onClick() function.

<! -- Copyright2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowersAdapter(private val onClick: (Flower) -> Unit) :
  ListAdapter<Flower, RecyclerView.ViewHolder>(FlowerDiffCallback())
Copy the code

In the Activity class, you pass in the click event function you just created when the Adapter is initialized.

<! -- Copyright2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

val flowersAdapter = FlowersAdapter { flower ->
  adapterOnClick(flower)
}
Copy the code

Add onClickHandler ()

Now that the response handling is defined, you can associate it to the Adapter ViewHolder.

Modify the ViewHolder to pass onClick() as an argument.

<! -- Copyright2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerViewHolder(itemView: View, val onClick: (Flower) -> Unit) :
  RecyclerView.ViewHolder(itemView)
Copy the code

In the initialized code, call the itemView’s setOnClickListener{}.

<! -- Copyright2019 Google LLC. 
    SPDX-License-Identifier: Apache-2.0 -->
 
 init{ itemView.setOnClickListener { currentFlower? .let { onClick(it) } } }Copy the code

Done! Now your RecyclerView can respond to click events.

Happy programming!

The next step

Check out the complete example with onClick().

Thank you for reading this third article in the RecyclerView series. Stay tuned for more RecyclerView in the future.

If you want to learn more about onClick(), please refer to the official documentation.