How to Handle Item Click for Android RecyclerView

How to Handle Item Click for Android RecyclerView

When we need to show large data set we use ListView, GridView or RecyclerView. RecyclerView is the advance version of ListView. It is used to show large number of items based on item template. In this article our primary objective is to create recycler view with custom button click listener. For the demo android application, we are going to create a shopping app view. In the shopping app view, we are going to show list of products. When user touched on any product we are going to display product name.

Before working on code check below demo video about what we are going to cover in this video.

As displayed​ in the above video in our demonstration app we have a main layout containing a RecyclerView with list of Products.

When we clicked on a product it displays product name.

Now it's time for coding.

First we need to add below line in our build.gradle (Module:app) file. (Do not forgot to click on sync)

Code

implementation 'com.android.support:recyclerview-v7:26.1.0'

Below is the code for activity_main.xml file.

Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content" android:layout_margin="5dp"
    android:id="@+id/llItemHolder"
    >
    <ImageView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id="@+id/ivItem"
        android:src="@drawable/camera" />
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="90dp"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/tvItemName"
            android:gravity="center_vertical"
            android:padding="2dp"
            android:lines="2"
            />
    </LinearLayout>
</LinearLayout>

RecyclerView item template activity_item_template.xml

Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content" android:layout_margin="5dp"
    android:id="@+id/llItemHolder"
    >
    <ImageView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id="@+id/ivItem"
        android:src="@drawable/camera" />
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="90dp"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/tvItemName"
            android:gravity="center_vertical"
            android:padding="2dp"
            android:lines="2"
            />
    </LinearLayout>
</LinearLayout>

RecyclerView Adapter File Name: RecyclerViewAdapter.java

Code

package com.vlemonn.blog.recyclerviewclick;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Mayank Sanghvi on 24-11-2017.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewItemHolder> {

    Context context;
    String[] arrItems;
    TypedArray images;

    private CustomButtonListener customButtonListener;

    public RecyclerViewAdapter(
            Context context
            ,String[] arrItems
            ,TypedArray images
            , CustomButtonListener customButtonListener) {
        this.context = context;
        this.arrItems = arrItems;
        this.images = images;
        this.customButtonListener = customButtonListener;
    }

    @Override
    public RecyclerViewItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater
                = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(
                R.layout.activity_item_template
                , parent
                , false);
        return new RecyclerViewItemHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerViewItemHolder holder, final int position) {
        final RecyclerViewItemHolder recyclerViewItemHolder = holder;
        recyclerViewItemHolder.tvItemName.setText(arrItems[position]);
        recyclerViewItemHolder.ivItem.setImageResource(images.getResourceId(position, -1));
        recyclerViewItemHolder.llItemHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(customButtonListener!=null)
                {
                    customButtonListener.onButtonClickListener(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return arrItems.length;
    }

    public void setCustomButtonListener(CustomButtonListener customButtonListener) {
        this.customButtonListener = customButtonListener;
    }
}

RecyclerViewItemHolder.java Item Holder File.

Code

package com.vlemonn.blog.recyclerviewclick;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by Mayank Sanghvi on 24-11-2017.
 */

class RecyclerViewItemHolder extends RecyclerView.ViewHolder{

    public ImageView ivItem;
    public TextView tvItemName;
    public LinearLayout llItemHolder;

    public RecyclerViewItemHolder(View itemView) {
        super(itemView);
        this.ivItem = itemView.findViewById(R.id.ivItem);
        this.tvItemName =  itemView.findViewById(R.id.tvItemName);
        this.llItemHolder =  itemView.findViewById(R.id.llItemHolder);
    }
}

MainActivity.java file code.

Code

package com.vlemonn.blog.recyclerviewclick;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements CustomButtonListener {

    private android.support.v7.widget.RecyclerView rvProducts;
    private ListAdapter listAdapter;

    String[] arrItems;
    TypedArray images;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        arrItems = getResources().getStringArray(R.array.itemName);
        images = getResources().obtainTypedArray(R.array.ItemImages);

        rvProducts = (RecyclerView) findViewById(R.id.rvProducts);
        LinearLayoutManager linearLayoutManager
                = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvProducts.setLayoutManager(linearLayoutManager);
        RecyclerViewAdapter recyclerViewAdapter
                = new RecyclerViewAdapter(
                this
                ,arrItems
                ,images
                ,this
            );
        rvProducts.setAdapter(recyclerViewAdapter);

    }

    @Override
    public void onButtonClickListener(int position) {
        showMessage(this,"Position: "+position+" - You clicked on "+arrItems[position]);
    }

    public void showMessage(Context context,String msg)
    {
        Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
    }
}

CustomButtonListener.java

Code

package com.vlemonn.blog.recyclerviewclick;

import android.widget.EditText;

/**
 * Created by Mayank Sanghvi on 10/5/2017.
 */

public interface CustomButtonListener {
    public void onButtonClickListener(int position);
}

strings.xml

Code

<resources>
    <string name="app_name">RecyclerViewClick</string>
    <string-array name="itemName">
        <item>Floppy</item>
        <item>Movie Camera</item>
        <item>Remote</item>
        <item>Smart Watch</item>
        <item>Mac Mini</item>
        <item>Monitor</item>
        <item>Graphics Card</item>
        <item>Zerox Machine</item>
        <item>Hdmi Cable</item>
        <item>Mouse</item>
        <item>Windows Phone</item>
        <item>PC Cabinet</item>
        <item>LCD</item>
        <item>Play Station</item>
        <item>Music Player</item>
        <item>Camera</item>
        <item>Tablet</item>
        <item>i Pad</item>
        <item>Smart Phone</item>
        <item>Keyboard</item>
        <item>Web Cam</item>
        <item>USB</item>
        <item>i Mac</item>
        <item>Laptop</item>
        <item>Game Controller</item>
        <item>Light Bulb</item>
        <item>Head Phones</item>
        <item>Camera 360</item>
        <item>Printer</item>
    </string-array>
    <string-array name="ItemImages">
        <item>@drawable/floppy</item>
        <item>@drawable/movie_camera</item>
        <item>@drawable/remote</item>
        <item>@drawable/smart_watch</item>
        <item>@drawable/mac_mini</item>
        <item>@drawable/monitor</item>
        <item>@drawable/graphics_card</item>
        <item>@drawable/zerox</item>
        <item>@drawable/hdmi</item>
        <item>@drawable/mouse</item>
        <item>@drawable/windows_phone</item>
        <item>@drawable/pc</item>
        <item>@drawable/lcd</item>
        <item>@drawable/playstation</item>
        <item>@drawable/music_player</item>
        <item>@drawable/camera_1</item>
        <item>@drawable/tablet</item>
        <item>@drawable/ipad</item>
        <item>@drawable/smartphone</item>
        <item>@drawable/keyboard</item>
        <item>@drawable/webcam</item>
        <item>@drawable/usb</item>
        <item>@drawable/imac</item>
        <item>@drawable/laptop</item>
        <item>@drawable/game_controller</item>
        <item>@drawable/light_bulb</item>
        <item>@drawable/headphones</item>
        <item>@drawable/camera</item>
        <item>@drawable/printer</item>
    </string-array>
</resources>

Drawable Folder Items

How to handle item click for RecyclerView Android

No changes in following files

  • styles.xml
  • colors.xml
  • AndroidManifest.xml

It's time to run our Android app.Below is the image for first run.

0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share