This post was initially written on Medium, But since I have started my development guide series on this blog itself, I have moved this post here. Thanks, everyone at Medium for ‘clapping’ and appreciating my writing.
I have read many complex posts on how to set onClickListener to RecyclerView before settling for this easy solution.
This post is the extension of the previous post: RecyclerView – The Easiest Approach
The recyclerView doesn’t come with setOnItemClickListener as ListView. I have seen many top ranked pages on Google which tells you to follow a custom approach. But what if I tell you that you can implement single item click listener on RecyclerView without any custom classes or interfaces.
That’s true. All you have to do is edit the RecyclerView Adapter and set ‘setOnClickListener’ to the ViewHolder. Let’s follow the example from official documentation.
Go to “Add a List Adapter” and copy the code. Now all you need to do is modify ViewHolder class and implement OnClickListener. Check out the code.
Backstory: When I wanted to implement this feature to my app, I first followed a wrong approach which would click on the random item if your recyclerView is large. Then I searched a lot on Google, StackOverflow, Youtube videos and personal Android blogs. Almost everyone suggested this method which looked complicated at first but I convinced myself to use it. But after some trial and errors, I finally cracked the best implementation which you see here.
Thanks for reading!