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.
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
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 :)