Open In App

How to Apply OnClickListener to RecyclerView Items in Android?

Last Updated : 22 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

As we know applying OnClickListener to a Button is very simple but applying OnClickListener to a RecyclerView item is different. In this article we first create a RecyclerView when we click a particular item of the RecyclerView then a new activity will be shown and display the name and email of the particular employee.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Note: Select Kotlin as the programming language.

Step 2: Add view binding support in gradle

Since in this project, we used ViewBinding so we have to set ViewBinding=True. Navigate to Gradle Scripts > build.gradle (Module:app) and add the Below buildFeatures section under the android section in the build.gradle (Module:app).

buildFeatures {
viewBinding = true
}

After adding this buildFeatures section, Sync the Project.


Step 3: Working with activity_main.xml

Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our application. It includes one RecyclerView on which our list of items is displayed. Comments are added inside the code for a better understanding of the Code.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<!--Here we Used ConstraintLayout for our project -->
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
   <androidx.appcompat.widget.Toolbar
       android:id="@+id/toolbar_main"
       android:layout_width="match_parent"
       app:title="GeeksForGeeks"
       app:titleTextColor="@color/white"
       android:layout_height="?attr/actionBarSize"
       android:background="#308d46"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

   <!--RecyclerView -->
   <androidx.recyclerview.widget.RecyclerView
       android:layout_width="match_parent"
       android:layout_height="0dp"
       app:layout_constraintTop_toBottomOf="@id/toolbar_main"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       android:id="@+id/rvItemsList"/>

</androidx.constraintlayout.widget.ConstraintLayout>


Step 4: Creating a layout for RecyclerView

Here we have to create a layout for our RecyclerView to display our items. Navigate to app > res > layout then Create a new layout resource file and name it items_row.xml. It includes three TextViews for displaying the Name and Emails of the Employees inside a CardView. Comments are added inside the code for a better understanding of the Code. To know more about CardView you can refer to this article.

items_row.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<!--LinearLayout orientation horizontal -->
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/llMain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp">

    <!--TextView for displaying Name -->
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:background="@color/white"
        android:foreground="?attr/selectableItemBackground"
        app:cardCornerRadius="3dp"
        app:cardElevation="3dp"
        app:cardUseCompatPadding="true">
      
        <!--LinearLayout orientation horizontal -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/black"
                android:textSize="20sp"
                tools:text="Name" />
          
            <!--TextView for displaying ":" -->
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" : "
                android:textSize="20dp"
                android:textStyle="bold" />

            <!--TextView for displaying Email -->
            <TextView
                android:id="@+id/tvEmail"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="#454545"
                android:textSize="16sp"
                tools:text="Email" />

        </LinearLayout>
      
    </androidx.cardview.widget.CardView>
  
</LinearLayout>


Step 5: Creating an Employee Model

In this step, we are going to create an employee model for our RecyclerView. It Contains the Employee's Name and Employee email Id, and it was going to be a Serializable model because we are going to pass the object of this Employee model to another Activity. Below is the code for the Employee model. Navigate to app >java > your package name >  Create a Java/Kotlin data class named it Employee.kt.

Employee.kt:

Kotlin
package org.geeksforgeeks.demo

import java.io.Serializable

// Employee model
data class Employee (
    // name of the employee
    val name:String,   
    
    // email of the employee
    val email:String   
): Serializable // serializing the model


Step 6: Creating Employee ArrayList

In this step, we are going to prepare the List of employees with the employee name and employee email. Below is the code for Creating and adding data to the ArrayList. Comments are added inside the code for a better understanding of the Code. Navigate to app > java >your package name > Create a Kotlin Object named Constants.

Constants.kt:

Kotlin
package org.geeksforgeeks.demo

object Constants {
    // This Method create an employee
    // Arraylist and return the Arraylist
    fun getEmployeeData():ArrayList<Employee>{
        // create an arraylist of type employee class
        val employeeList=ArrayList<Employee>()
        val emp1=Employee("Chinmaya Mohapatra","[email protected]")
        employeeList.add(emp1)
        val emp2=Employee("Ram prakash","[email protected]")
        employeeList.add(emp2)
        val emp3=Employee("OMM Meheta","[email protected]")
        employeeList.add(emp3)
        val emp4=Employee("Hari Mohapatra","[email protected]")
        employeeList.add(emp4)
        val emp5=Employee("Abhisek Mishra","[email protected]")
        employeeList.add(emp5)
        val emp6=Employee("Sindhu Malhotra","[email protected]")
        employeeList.add(emp6)
        val emp7=Employee("Anil sidhu","[email protected]")
        employeeList.add(emp7)
        val emp8=Employee("Sachin sinha","[email protected]")
        employeeList.add(emp8)
        val emp9=Employee("Amit sahoo","[email protected]")
        employeeList.add(emp9)
        val emp10=Employee("Raj kumar","[email protected]")
        employeeList.add(emp10)

        return  employeeList
    }
}


Step 7: Create an Adapter for our RecyclerView and Apply OnClickListener to it

As we know for every RecyclerView we need an Adapter class.  and Implement the Three member functions.

  • onCreateViewHolder: Here we have to connect the layout resource file that we are for our RecyclerView. 
  • onBindViewHolder: Here we have to bind our items to the data source.
  • getItemCount: Here we have to return the length of our ArrayList.

Here we are going to Apply OnClickListener to our RecyclerView Adapter by Implementing OnClickListener Interface. Navigate to app > java >your package name > Create a Kotlin Object named as ItemAdapter.Below is the code for the ItemAdapter class. Comments are added inside the code for a better understanding of the Code.

ItemAdapter.kt:

Kotlin
package org.geeksforgeeks.demo

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.geeksforgeeks.demo.databinding.ItemsRowBinding

class ItemAdapter(
    private val items: ArrayList<Employee>
) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
    private var onClickListener: OnClickListener? = null

    // Inflate the layout and return a new ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemsRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    // Bind the data to the view holder and set click listeners
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.binding.tvName.text = item.name
        holder.binding.tvEmail.text = item.email

        // Set click listener for the item view
        holder.itemView.setOnClickListener {
            onClickListener?.onClick(position, item)
        }
    }

    // Return the size of the items list
    override fun getItemCount(): Int {
        return items.size
    }

    // Set the click listener for the adapter
    fun setOnClickListener(listener: OnClickListener?) {
        this.onClickListener = listener
    }

    // Interface for the click listener
    interface OnClickListener {
        fun onClick(position: Int, model: Employee)
    }

    // ViewHolder class to hold the views
    class ViewHolder(val binding: ItemsRowBinding) : RecyclerView.ViewHolder(binding.root)
}


Step 8: Working with MainActivity File

In this step, we are going to Get the employeelist by calling the Constants getEmployeeData() method and assign the employee list to the ItemAdapter and display the employee list. and apply the adapter to an OnClickListener and pass an object to another activity(EmployeeDetails). Below is the code for the MainActivity. Comments are added inside the code for a better understanding of the Code.

MainActivity.kt:

Kotlin
package org.geeksforgeeks.demo

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import org.geeksforgeeks.demo.databinding.ActivityMainBinding

// In this project we are going to use view binding
class MainActivity : AppCompatActivity() {

    // View Binding
    private val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        // getting the employee list by
        // calling getEmployeeData method
        val employeeList= Constants.getEmployeeData()
        binding.rvItemsList.layoutManager = LinearLayoutManager(this)
        binding.rvItemsList.setHasFixedSize(true)

        // Creating an instance of the
        // adapter and passing employeeList to it
        val adapter = ItemAdapter(employeeList)

        // Assign ItemAdapter instance to our RecyclerView
        binding.rvItemsList.adapter = adapter

        // Applying OnClickListener to our Adapter
        adapter.setOnClickListener(object :
            ItemAdapter.OnClickListener {
            override fun onClick(position: Int, model: Employee) {
                val intent = Intent(this@MainActivity, EmployeeDetails::class.java)
                // Passing the data to the
                // EmployeeDetails Activity
                intent.putExtra(NEXT_SCREEN, model)
                startActivity(intent)
            }
        })
    }
    companion object{
        const val NEXT_SCREEN="details_screen"
    }
}


Step 9: Creating an EmployeeDetails Activity

In this step, we are going to create a new activity that displays the name and email of the employee. When we click an item of the RecyclerView then this activity will be shown and display the name and email of the particular employee, and receive the object of type Employee sent by our MainActivity. Below is the code for EmployeeDetailsActivity. Comments are added inside the code for a better understanding of the Code.

EmployeeDetails.kt:

Kotlin
package org.geeksforgeeks.demo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.geeksforgeeks.demo.databinding.ActivityEmployeeDetailsBinding

class EmployeeDetails : AppCompatActivity() {
    private val binding: ActivityEmployeeDetailsBinding by lazy {
        ActivityEmployeeDetailsBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        binding.toolbar.setNavigationOnClickListener {
            onBackPressed()
        }

        // creating an employee list
        // of type Employee class
        var employeeDetails:Employee?=null

        // checking if the intent has extra
        if(intent.hasExtra(MainActivity.NEXT_SCREEN)){
            // get the Serializable data model class with the details in it
            employeeDetails =
                intent.getSerializableExtra(MainActivity.NEXT_SCREEN) as Employee
        }
        // it the employeeDetails is not null the it has some data and display it
        if(employeeDetails!=null){
            binding.displayName.text= employeeDetails.name   // displaying name
            binding.displayEmail.text= employeeDetails.email // displaying email
        }
    }
}


Step 10: Working with activity_employee_details.xml

In this step we are going to create the layout for our EmployeeDetails Activity, it will display the name and email of the particular employee. Below is the code for activity_employee_details.xml.

activity_employee_details.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<!-- Constaintlayout -->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EmployeeDetails">
    
      <!--Custom ToolBar -->
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#308d46"
        app:titleTextColor="@color/white"
        app:title="EmployeeDetails"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
      <!-- LinearLayout to place items vertically-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintTop_toBottomOf="@id/toolbar">
        
          <!-- LinearLayout to place items horizontally-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name : "
                android:id="@+id/name"
                android:layout_margin="10dp"
                android:textStyle="bold"
                android:textSize="25sp"
                android:textColor="@color/black"
                />
            <TextView
                android:id="@+id/display_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" name display"
                android:layout_margin="10dp"
                android:textSize="25sp"
                android:textColor="@color/black"
                />

        </LinearLayout>
        
          <!-- LinearLayout to place items horizontally-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Email : "
                android:id="@+id/email"
                android:layout_margin="10dp"
                android:textStyle="bold"
                android:textSize="25sp"
                android:textColor="@color/black"
                />
            <TextView
                android:id="@+id/display_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" name display"
                android:textColor="@color/black"
                android:layout_margin="10dp"
                android:textSize="25sp"
                />

        </LinearLayout>
      
    </LinearLayout>
  
</androidx.constraintlayout.widget.ConstraintLayout>

Output:


Next Article

Similar Reads