Ultimate Programmer Super Stack

If you’ve used a RecyclerView, you may know that they don’t have a setOnItemClickListener as ListView had, so we have to create our own way to do it. Many people asked me how to do this, so that’s why I decided to write about it.

There are many ways to achieve this, but I will show you the way I usually do it. My mechanism consists of passing the listener as a parameter to the constructor and then assign it when I bind the data to the view in onBindViewHolder.

You’ll first need an interface that specifies listener’s behaviour. In this example, there is a sample model called ContentItem, so the click will return an item of that type:

The constructor will receive an object that implements this interface, along with the items to be rendered:

You could alternatively create a setOnItemClickListener method and assign it that way. Now, in onBindViewHolder the ViewHolder will receive the constructor in the custom bind method:

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

This is how this bind method looks:

Use it whenever you need it by creating a new adapter and the listener that will implement the behaviour when an item is clicked. A simple example:

Take a look at the whole code of this adapter. Of course there are many alternatives here. In the end, the implementation is left to the developer when using RecyclerView, so choose whatever fits better in your situation.

Author: Antonio Leiva

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.


%d bloggers like this: