Click listener for RecyclerView adapter

There is a common pattern I use in all of my RecyclerView adapters to listen for click events on each item.

I created an interface that is similar to the normal click listener, except it also has the position as a parameter.

With this interface I can set up a view holder class as a click listener, and pass in an instance of my interface. Then I set the view itself as a click listener and call my interface with the appropriate position.

In your case you may not want to set the entire view as a click listener, maybe you have a button inside your layout. You can set it on that instead if you want, or add multiple listeners if you have multiple buttons for example. This is just a simple example to demonstrate how it works.

Now that I have a view holder, I can use it in my adapter.

I pass in my interface to the adapter so it can pass it to the view holder. There is only 1 instance of this listener, all of the views call back to the same instance. Since they are differentiated by the position being passed in, there’s no need to have multiple instances. I create this listener when the adapter is instantiated.

Lastly, here is an example of a fragment where I create this listener.

I am simply toasting the position that was tapped on, but you could do anything with the data at this point. For example you may have a list of notes, and tapping on one gives you its position in the list. With that you can get the data object from the list and display the details of that note to the user.

Pierce Zaifman

Android app developer. Hates wasting time and takes satisfaction in improving efficiency in all aspects of life. Also enjoys helping people solve their problems.

London, Ontario, Canada

Subscribe to Pierce Zaifman

Get the latest posts delivered right to your inbox.

or subscribe via RSS.