Handling click events in RecyclerView

For my next trick, I will write about onClick()

Meghan Mehta
Android Developers

--

This is the third in a series of articles which cover the fundamentals of creating and using RecyclerView. If you already have a solid understanding of how to create a RecyclerView, then carry on. Otherwise, consider starting with this post.

When displaying a list of data with RecyclerView, you may want to have a response when an item is clicked. This response could open a new page with more data, present a toast, remove an item, etc. The possibilities are endless but they are all done using onClick().

Defining the click action

Before creating the listener, create a function in the Activity class that performs the action to be done upon click.

Next, update the Adapter’s constructor to take in the onClick() function.

In the Activity class, pass in the newly created function when you initialize the Adapter.

Adding the onClickHandler()

Now that the action is defined, it is time to attach it to the ViewHolder in the Adapter.

Update the ViewHolder to take in onClick() as a parameter.

In the initializer, call setOnClickListener{} on the itemView.

That’s it! Your RecyclerView is now responsive so time to get your click on!

Happy coding!

Next Steps

The full code sample including onClick() can be found here.

Thank you for reading the third installment in my RecyclerView series! Stay tuned as I write about more RecyclerView features.

If you want to learn more about onClick() check out the documentation.

--

--