Image for post
Image for post

Handling click events in RecyclerView

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

Meghan Mehta
Jan 8 · 2 min read

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

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()

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

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.

Android Developers

The official Android Developers publication on Medium

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store