How to Apply OnClickListener to RecyclerView Items in Android?
Last Updated :
27 Mar, 2023
As we know applying OnClickListener to a Button is very simple but applying OnClickListener to a RecylerView item is different. In this article we first create a RecylerView 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. A sample video is given below to get an idea about what we are going to do in this article.
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 that select Kotlin as the programming language.
Step 2: Add buildFeatures to build.gradle (Module:app)
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
}
Android Section:
android {
namespace 'com.example.geeksforgeeks'
compileSdk 32
defaultConfig {
applicationId "com.example.geeksforgeeks"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding = true
}
}
After adding this buildFeatures section, Sync the Project.
Step 3: Change the StatusBar Color
Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.
<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>
Step 4: 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.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout
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" />
< 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 5: 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 Text Views 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
android:id = "@+id/llMain"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center_vertical"
android:orientation = "horizontal"
android:padding = "10dp" >
< 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
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
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = " : "
android:textSize = "20dp"
android:textStyle = "bold" />
< 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 6: 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 Kotlin data class named it Employee.kt.
Employee.kt:
Kotlin
package com.example.geeksforgeeks
import android.os.Parcel
import android.os.Parcelable
data class Employee(
val name:String,
val email:String
):java.io.Serializable
|
Java
package com.example.geeksforgeeks;
import java.io.Serializable;
public class Employee implements Serializable {
private final String name;
private final String email;
public Employee(String name, String email) {
this .name = name;
this .email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
|
Step 7: 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 com.example.geeksforgeeks
object Constants {
fun getEmployeeData():ArrayList<Employee>{
val employeeList=ArrayList<Employee>()
val emp1=Employee( "Chinmaya Mohapatra" , "chinmaya@gmail.com" )
employeeList.add(emp1)
val emp2=Employee( "Ram prakash" , "ramp@gmail.com" )
employeeList.add(emp2)
val emp3=Employee( "OMM Meheta" , "mehetaom@gmail.com" )
employeeList.add(emp3)
val emp4=Employee( "Hari Mohapatra" , "harim@gmail.com" )
employeeList.add(emp4)
val emp5=Employee( "Abhisek Mishra" , "mishraabhi@gmail.com" )
employeeList.add(emp5)
val emp6=Employee( "Sindhu Malhotra" , "sindhu@gmail.com" )
employeeList.add(emp6)
val emp7=Employee( "Anil sidhu" , "sidhuanil@gmail.com" )
employeeList.add(emp7)
val emp8=Employee( "Sachin sinha" , "sinhas@gmail.com" )
employeeList.add(emp8)
val emp9=Employee( "Amit sahoo" , "sahooamit@gmail.com" )
employeeList.add(emp9)
val emp10=Employee( "Raj kumar" , "kumarraj@gmail.com" )
employeeList.add(emp10)
return employeeList
}
}
|
Java
package com.example.geeksforgeeks;
import java.util.ArrayList;
public class Constants {
public static ArrayList<Employee> getEmployeeData() {
ArrayList<Employee> employeeList = new ArrayList<>();
Employee emp1 = new Employee( "Chinmaya Mohapatra" , "chinmaya@gmail.com" );
employeeList.add(emp1);
Employee emp2 = new Employee( "Ram prakash" , "ramp@gmail.com" );
employeeList.add(emp2);
Employee emp3 = new Employee( "OMM Meheta" , "mehetaom@gmail.com" );
employeeList.add(emp3);
Employee emp4 = new Employee( "Hari Mohapatra" , "harim@gmail.com" );
employeeList.add(emp4);
Employee emp5 = new Employee( "Abhisek Mishra" , "mishraabhi@gmail.com" );
employeeList.add(emp5);
Employee emp6 = new Employee( "Sindhu Malhotra" , "sindhu@gmail.com" );
employeeList.add(emp6);
Employee emp7 = new Employee( "Anil sidhu" , "sidhuanil@gmail.com" );
employeeList.add(emp7);
Employee emp8 = new Employee( "Sachin sinha" , "sinhas@gmail.com" );
employeeList.add(emp8);
Employee emp9 = new Employee( "Amit sahoo" , "sahooamit@gmail.com" );
employeeList.add(emp9);
Employee emp10 = new Employee( "Raj kumar" , "kumarraj@gmail.com" );
employeeList.add(emp10);
return employeeList;
}
}
|
Step 8: Create an Adapter for our RecylerView and Apply OnClickListener to it
As we know for every RecylerView 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 RecylerView.
- 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 RecylerView 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 com.example.geeksforgeeks
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.geeksforgeeks.databinding.ItemsRowBinding
class ItemAdapter(
private val items: ArrayList<Employee>
) :
RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
private var onClickListener: OnClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ItemsRowBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.tvName.text = item.name
holder.tvEmail.text = item.email
holder.itemView.setOnClickListener {
if (onClickListener != null ) {
onClickListener!!.onClick(position, item )
}
}
}
override fun getItemCount(): Int {
return items.size
}
fun setOnClickListener(onClickListener: OnClickListener) {
this .onClickListener = onClickListener
}
interface OnClickListener {
fun onClick(position: Int, model: Employee)
}
class ViewHolder(binding: ItemsRowBinding) : RecyclerView.ViewHolder(binding.root) {
val tvName = binding.tvName
val tvEmail = binding.tvEmail
}
}
|
Java
package com.example.geeksforgeeks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.example.geeksforgeeks.databinding.ItemsRowBinding;
import java.util.ArrayList;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private ArrayList<Employee> items;
private OnClickListener onClickListener;
public ItemAdapter(ArrayList<Employee> items) {
this .items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(ItemsRowBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false ));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Employee item = items.get(position);
holder.tvName.setText(item.getName());
holder.tvEmail.setText(item.getEmail());
holder.itemView.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onClickListener != null ) {
onClickListener.onClick(position, item);
}
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public void setOnClickListener(OnClickListener onClickListener) {
this .onClickListener = onClickListener;
}
public interface OnClickListener {
void onClick( int position, Employee model);
}
static class ViewHolder extends RecyclerView.ViewHolder {
ItemsRowBinding binding;
ViewHolder(ItemsRowBinding binding) {
super (binding.getRoot());
this .binding = binding;
}
final ItemsRowBinding getBinding() {
return binding;
}
final void setBinding(ItemsRowBinding binding) {
this .binding = binding;
}
final void setTvName(CharSequence value) {
binding.tvName.setText(value);
}
final void setTvEmail(CharSequence value) {
binding.tvEmail.setText(value);
}
final CharSequence getTvName() {
return binding.tvName.getText();
}
final CharSequence getTvEmail() {
return binding.tvEmail.getText();
}
}
}
|
Step 9: 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 com.example.geeksforgeeks
import android.Manifest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.geeksforgeeks.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
var binding:ActivityMainBinding?= null
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
val emplist=Constants.getEmployeeData()
binding?.rvItemsList?.layoutManager = LinearLayoutManager( this )
binding?.rvItemsList?.setHasFixedSize( true )
val ItemAdapter = ItemAdapter(emplist)
binding?.rvItemsList?.adapter = ItemAdapter
ItemAdapter.setOnClickListener(object :
ItemAdapter.OnClickListener {
override fun onClick(position: Int, model: Employee) {
val intent = Intent( this @MainActivity , EmployeeDetails:: class .java)
intent.putExtra(NEXT_SCREEN, model)
startActivity(intent)
}
})
}
companion object{
val NEXT_SCREEN= "details_screen"
}
}
|
Java
package com.example.geeksforgeeks;
import android.Manifest;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.geeksforgeeks.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
final ArrayList<Employee> emplist = Constants.getEmployeeData();
binding.rvItemsList.setLayoutManager( new LinearLayoutManager( this ));
binding.rvItemsList.setHasFixedSize( true );
final ItemAdapter ItemAdapter = new ItemAdapter(emplist);
binding.rvItemsList.setAdapter(ItemAdapter);
ItemAdapter.setOnClickListener( new ItemAdapter.OnClickListener() {
@Override
public void onClick( int position, Employee model) {
Intent intent = new Intent(MainActivity. this , EmployeeDetails. class );
intent.putExtra(NEXT_SCREEN, model);
startActivity(intent);
}
});
}
public static final String NEXT_SCREEN = "details_screen" ;
}
|
Step 10: 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 RecylerView 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 com.example.geeksforgeeks
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.geeksforgeeks.databinding.ActivityEmployeeDetailsBinding
class EmployeeDetails : AppCompatActivity() {
var binding:ActivityEmployeeDetailsBinding?= null
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
binding= ActivityEmployeeDetailsBinding.inflate(layoutInflater)
setContentView(binding?.root)
setSupportActionBar(binding?.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled( true )
binding?.toolbar?.setNavigationOnClickListener {
onBackPressed()
}
var emplist:Employee?= null
if (intent.hasExtra(MainActivity.NEXT_SCREEN)){
emplist =
intent.getSerializableExtra(MainActivity.NEXT_SCREEN) as Employee
}
if (emplist!= null ){
binding?.displayName?.text=emplist!!.name
binding?.displayEmail?.text=emplist!!.email
}
}
}
|
Java
package com.example.geeksforgeeks;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.geeksforgeeks.databinding.ActivityEmployeeDetailsBinding;
public class EmployeeDetails extends AppCompatActivity {
private ActivityEmployeeDetailsBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
binding = ActivityEmployeeDetailsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled( true );
binding.toolbar.setNavigationOnClickListener(view -> onBackPressed());
Employee emplist = null ;
if (getIntent().hasExtra(MainActivity.NEXT_SCREEN)) {
emplist = (Employee) getIntent().getSerializableExtra(MainActivity.NEXT_SCREEN);
}
if (emplist != null ) {
binding.displayName.setText(emplist.getName());
binding.displayEmail.setText(emplist.getEmail());
}
}
}
|
Step 11: 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" ?>
< androidx.constraintlayout.widget.ConstraintLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".EmployeeDetails" >
< 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
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical"
app:layout_constraintTop_toBottomOf = "@id/toolbar" >
< 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
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...