Android RecyclerView OnItemClickListener

In This Tutorial

Here we learn how to handle onClick and onLongPress on an recyclerview item. In an android for listview we have a predefine onItemClickListener available to detect item click but their is no RecyclerView onItemClickListener available. So we have to implement our own methods to detect item click.

RecyclerView OnItemClickListener

Prerequisite

This tutorial is in continuation, required knowledge about the working of recyclerview. You can learn about how to implement android recyclerview with dividers from here


Download

The source code for this post is available at GitHub. You can download/checkout this from here


Your own recyclerView OnItemClickListener

There are two ways to handle onClick and onLongClick on item of recyclerview.

1. First, implement View.OnClickListener, View.OnLongClickListener in your ViewHolder creation, which is tightly coupled way to detect onclick and onLongClick. This method is also much useful if you want to attach an onClick listener to a specific item within the item view, you should probably do that in your adapter, in onBindViewHolder or in your viewholder itself.

2. Second, create a custom class which implement RecyclerView.OnItemTouchListener which is a less tightly coupled way to detect click on whole item view. But using this we are not able to detect click on specific item within the item view.

1. Implment OnClickListener and OnLongClickListener to your ViewHolder

1. Interface

In your adapter class, Create an interface.

2. Adapter

In your adapter class, create a setter method to reference interface OnItemClickListener

3. ViewHolder

Implement View.OnClickListener, View.OnLongClickListener to your viewholder

4. MainActivity.java

In your activity class set an adapter OnItemClickListener.


2. Creating a custom class which implement RecyclerView.OnItemTouchListener


The second way to implement your own recyclerView OnItemClickListener is by creating a custom class which implements RecyclerView.OnItemTouchListener.

1. RecyclerItemTouchListener.java

2. MainActivity.java

In your activity set RecyclerView OnItemTouchListener.

About Jitendra Singh

Hi there, I'm a founder at androidfizz and a career oriented entity in an area of development of android based mobile applications.

View all posts by Jitendra Singh →

Leave a Reply

Your email address will not be published. Required fields are marked *