RecyclerView Item Click in a Better Way

RecyclerView is the most popular view in Android world. Today I wanna show you a better approach for clicking an item. We are using Kotlin and if you don’t you should :) Also there is a Turkish version of this story check the link

Most popular way

In my experience, the most way that I saw is creating an Interface than pass it to Activity or Fragment by implementing it. After that adapter takes it as an argument and set it in OnBindViewHolder.

We have Kotlin and we can just use Lambda to achieve the same behavior as having the interface class in Java. So forgot about using interfaces.

So lets begin with coding adapter!

Here is the most popular part. We can easily handle clicks in OnBindViewHolder, because we have position and data.

But there is a performance problem in this approach. In RecyclerView, the onBindViewHolder gets called every time the ViewHolder is bound and the setOnClickListener will be triggered too. So setting click event here is not best way.

Better Way

Setting a click listener in onCreateViewHolder which invokes only when a ViewHolder gets created can be preferable.

Maybe you wonder the position of item but in ViewHolder class there is here which is absoluteAdapterPosition.

So show me the all code !

Fragment or Activity

Adapter

ViewHolder

I think setting a click listener of the RecyclerView item in onCreateViewHolder is a best way since it reduces the function call significantly compared to doing it in onBindViewHolder.

Do not forget claps, happy coding :)

--

--

--

Senior Android Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

RxJava 2 chaining and conventional code side by side comparison

Preferred way to set clickable image icon

The first step on your KMP journey — changing your microservices.

How Flutter 2.8 Enhance Mobile App Performance?

Breaking deep-link unknowing by adding another deep-link

Implement Appium Test in BrowserStack

Safe & Simple REST API call in Android with Kotlin coroutines + Lambda

Deploy to Huawei AppGallery — Verified Bitrise Step

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
Emre Hamurcu

Emre Hamurcu

Senior Android Developer

More from Medium

Implementing Glassmorphism in Android App

S.O.L.I.D Principles in Android Development

Debugging like a pro in Android Studio