Open In App

How to Implement Item Click Interface in Android?

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. 

What we are going to build in this article?

In this article, we will be using a recycler view with many items. An item is made using CardView which further consists of TextView to show the required text to a user. When a user clicks on any item it displays the position and value of that item. Note that we are going to implement this project in both Java & Kotlin Language. Here is a sample video of the application which we are going to build.

Step by Step Implementation

Step 1: Create a new project

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

Step 2: Working with XML files

Navigate to the app > res > layout > activity_main.xml and make the following changes. Then, right click on the layout folder and select New > Layout Resource File and name the file as item_main.xml and make the following changes.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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">

    <!--Recycler view-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/item_main" />

</androidx.constraintlayout.widget.ConstraintLayout>
item_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    app:cardCornerRadius="8dp">

    <TextView
        android:id="@+id/text_View"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dp"
        android:textSize="20sp" />

</androidx.cardview.widget.CardView>


Step 3: Create a new interface

Navigate to app > java > {package-name}, right click on the folder and select, New > Java/Kotlin Class/File and create a new file named as ItemClickListener. Now make the following changes to the file.

ItemClickListener.java
package org.geeksforgeeks.demo;

public interface ItemClickListener {
    void onClick(int position,String value);
}
ItemClickListener.kt
package org.geeksforgeeks.demo

interface ItemClickListener {
    fun onClick(position: Int, value: String?)
}


Step 4: Create a new adapter class

Navigate to app > java > {package-name}, right click on the folder and select, New > Java/Kotlin Class/File and create a new file named as MainAdapter. Now make the following changes to the file.

MainAdapter.java
package org.geeksforgeeks.demo;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {

    // initialize variables
    private ArrayList<String> arrayList;
    private ItemClickListener itemClickListener;
    private int selectedPosition = -1;

    public MainAdapter(ArrayList<String> arrayList, ItemClickListener itemClickListener) {
        this.arrayList = arrayList;
        this.itemClickListener = itemClickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Initialize view
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_main, parent, false);
        // return holder
        return new ViewHolder(view);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // set value on text view
        holder.textView.setText(arrayList.get(position));

        holder.itemView.setOnClickListener(v -> {
            // get adapter position
            int clickedPosition = holder.getAbsoluteAdapterPosition();
            // call listener
            itemClickListener.onClick(clickedPosition, arrayList.get(clickedPosition));
            // update position
            selectedPosition = clickedPosition;
            // notify
            notifyDataSetChanged();
        });

        // When current position is equal to selected position
        if (selectedPosition == position) {
            // set black background color
            holder.cardView.setCardBackgroundColor(Color.parseColor("#000000"));
            // set white text color
            holder.textView.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            // when current position is different
            // set white background
            holder.cardView.setCardBackgroundColor(Color.parseColor("#FFFFFF"));
            // set black text color
            holder.textView.setTextColor(Color.parseColor("#000000"));
        }
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // initialize variable
        CardView cardView;
        TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.card_view);
            textView = itemView.findViewById(R.id.text_View);
        }
    }
}
MainAdapter.kt
package org.geeksforgeeks.demo

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView

class MainAdapter(
    // initialize variables
    private var arrayList: ArrayList<String>,
    private val itemClickListener: ItemClickListener
) :
    RecyclerView.Adapter<MainAdapter.ViewHolder>() {
    private var selectedPosition: Int = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        // Initialize view
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_main, parent, false)
        // return holder
        return ViewHolder(view)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // set value on text view
        holder.textView.text = arrayList[position]

        holder.itemView.setOnClickListener {
            // get adapter position
            val clickedPosition = holder.absoluteAdapterPosition
            // call listener
            itemClickListener.onClick(clickedPosition, arrayList[clickedPosition])
            // update position
            selectedPosition = clickedPosition
            // notify
            notifyDataSetChanged()
        }

        // When current position is equal to selected position
        if (selectedPosition == position) {
            // set black background color
            holder.cardView.setCardBackgroundColor(Color.parseColor("#000000"))
            // set white text color
            holder.textView.setTextColor(Color.parseColor("#FFFFFF"))
        } else {
            // when current position is different
            // set white background
            holder.cardView.setCardBackgroundColor(Color.parseColor("#FFFFFF"))
            // set black text color
            holder.textView.setTextColor(Color.parseColor("#000000"))
        }
    }

    override fun getItemCount(): Int = arrayList.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // initialize variable
        var cardView: CardView = itemView.findViewById(R.id.card_view)
        var textView: TextView = itemView.findViewById(R.id.text_View)
    }
}


Step 5: Working with MainActivity file

Go to the MainActivity file and refer to the following code. Comments are added inside the code to understand the code in more detail.

MainActivity.java
package org.geeksforgeeks.demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    // initialize variable
    RecyclerView recyclerView;
    ArrayList<String> arrayList=new ArrayList<>();
    MainAdapter adapter;
    ItemClickListener itemClickListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // assign variable
        recyclerView=findViewById(R.id.recycler_view);

        // use for loop
        for(int i=0;i<15;i++)
        {
            // add values in array list
            arrayList.add("Address "+i);
        }
      
        // Initialize listener
        itemClickListener=new ItemClickListener() {
            @Override
            public void onClick(int position, String value) {
                // Display toast
                Toast.makeText(getApplicationContext(),"Position : "
                +position +" || Value : "+value,Toast.LENGTH_SHORT).show();
            }
        };

        // set layout manager
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // Initialize adapter
        adapter=new MainAdapter(arrayList,itemClickListener);
        // set adapter
        recyclerView.setAdapter(adapter);

    }
}
MainActivity.kt
package org.geeksforgeeks.demo

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    // initialize variable
    private lateinit var recyclerView: RecyclerView
    private var arrayList: ArrayList<String> = ArrayList()
    private var adapter: MainAdapter? = null
    private var itemClickListener: ItemClickListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // assign variable
        recyclerView = findViewById(R.id.recycler_view)

        // use for loop
        for (i in 0..14) {
            // add values in array list
            arrayList.add("Address $i")
        }


        // Initialize listener
        itemClickListener = object : ItemClickListener {
            override fun onClick(position: Int, value: String?) {
                // Display toast
                Toast.makeText(
                    this@MainActivity, ("Position : "
                            + position + " || Value : " + value), Toast.LENGTH_SHORT
                ).show()
            }
        }

        // set layout manager
        recyclerView.setLayoutManager(LinearLayoutManager(this))
        // Initialize adapter
        adapter = MainAdapter(arrayList, itemClickListener as ItemClickListener)
        // set adapter
        recyclerView.setAdapter(adapter)
    }
}

Output:


Next Article
Practice Tags :

Similar Reads