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:

Join my free 2-hour training!

  • Learn how to start and use a more idiomatic Kotlin in a breeze
  • Find out what's the current situation of Kotlin in the market
  • Get 2 free ebooks just for attending!

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.


%d bloggers like this: