Open In App

How to Implement Item Click Interface in Android?

Last Updated : 27 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
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 Java 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

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can 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 add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycler_view"
        tools:listitem="@layout/item_main"
        />
  
</androidx.constraintlayout.widget.ConstraintLayout>


Follow the path app > res > layout > right click > new > layout resource file and create a new file named as item_main.xml. Use the below code in item_main.xml file-

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/card_view"
    android:layout_margin="4dp"
    app:cardCornerRadius="8dp"
    >
  
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_View"
        android:textSize="20sp"
        android:padding="20dp"
        android:gravity="center"
        />
  
</androidx.cardview.widget.CardView>


Step 3: Working with java files

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

Java




package com.example.itemclickinterface;
  
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);
  
    }
}


Follow the path app > java > com.example.multiple_item_delete > right click > new > java class and create a new file named as MainAdapter.java. Use the below code in MainAdapter.java file-

Java




package com.example.itemclickinterface;
  
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
       // initialize variables
    ArrayList<String> arrayList;
    ItemClickListener itemClickListener;
    int selectedPosition=-1;
  
    // create constructor
    public MainAdapter(ArrayList<String> arrayList,ItemClickListener itemClickListener)
    {
        this.arrayList=arrayList;
        this.itemClickListener=itemClickListener;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull 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);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
  
        // set value on text view
        holder.textView.setText(arrayList.get(position));
  
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // get adapter position
                int position=holder.getAdapterPosition();
                // call listener
                itemClickListener.onClick(position,arrayList.get(position));
                // update position
                selectedPosition=position;
                // notify
                notifyDataSetChanged();
            }
        });
  
        // check conditions
        if(selectedPosition==position)
        {
            // When current position is equal 
             // to selected 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 array list size
        return arrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // initialize variable
        CardView cardView;
        TextView textView;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // assign variable
            cardView=itemView.findViewById(R.id.card_view);
            textView=itemView.findViewById(R.id.text_View);
        }
    }
}


Follow the path app > java > com.example.multiple_item_delete > right click > new > interface and create a new file named as ItemClickListener.java. Use the below code in MainAdapter.java file-

Java




package com.example.itemclickinterface;
  
public interface ItemClickListener {
    void onClick(int position,String value);
}


Here is the final output of the application.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads