, AndroidMkab

Android RecyclerView With CardView Example

Android RecyclerView is the most common View used in Android Apps for showing large data as well as dynamic data. RecyclerView is usually used for Feeds, Showing list of items. Adding CardView to RecyclerView adds beauty to the recyclerView.

In this post I will show you how to add Android RecyclerView with CardView in your Android Studio Project.

Project Specification I used:

  1. Android Studio 3.6.3
  2. Target API 29 with AndroidX support

implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation "androidx.cardview:cardview:1.0.0"

Dependencies:

Next Add Android RecycerView to your Layout XML FIle in my case activity_main.xml

 <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/mRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

Next we have to design an XML Layout for RecyclerView Items. For that create new layout xml file with name items_home.xml (You can also give different name). next add below code to your items_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_margin="5dp"
    android:layout_centerHorizontal="true"
    android:id="@+id/lyt_parent">
        <androidx.cardview.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:layout_above="@+id/tvTitle"
            card_view:cardElevation="5dp"
            card_view:cardUseCompatPadding="true"
            card_view:cardCornerRadius="4dp">



                <ImageView
                    android:id="@+id/thumb"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="fitXY"/>



        </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textSize="14sp"
        android:singleLine="true"
        android:textColor="@android:color/black"/>
</RelativeLayout>

Next go to your MainActivity.java file and create a variable for Recyclerview before onCreate method

 RecyclerView recyclerView;

Next initiate the RecyclerView and add some properties and GridLayout Manager with span count 2 inside onCreate method

recyclerView = findViewById(R.id.mRecyclerView);

        // Add LayoutManager for Recyler View
       GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);

        // Add Some behavioral propeerties to RecyclerView (Optional)
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemViewCacheSize(20);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setDrawingCacheEnabled(true);
        recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

Next add some Arrays of data to show inside recyclerview

 final String[] titles = {"Arq 2016", "Barry 2016","Beasts of no nation 2015", "Deidra Laney rob a train 2017",
                "Iboy 2017", "Imperial dreams 2014","Journey to greenland 2016", "Pandora 2016",
                "Spectral 2016", "Tallulah 2016","The discovery 2017", "The ridiculous 6 2015",
                "True memoirs of an international assassin 2016", "XOXO 2016"};
        int[] images = {R.drawable.arq_2016, R.drawable.barry_2016,R.drawable.beasts_of_no_nation_2015, R.drawable.deidra_laney_rob_a_train_2017,
                R.drawable.iboy_2017, R.drawable.imperial_dreams_2014,R.drawable.journey_to_greenland_2016, R.drawable.pandora_2016,
                R.drawable.spectral_2016, R.drawable.tallulah_2016,R.drawable.the_discovery_2017, R.drawable.the_ridiculous_6_2015,
                R.drawable.true_memoirs_of_an_international_assassin_2016, R.drawable.xoxo_2016,};

Note: Make sure you copied above mentioned images into you drawable folder

Next we have to create RecyclerView Adapter file in Java. For that create new Java file with name AdapterRecyclerView inside adapter folder and copy below code and replace with your code inside it.

package com.androidmkab.recyclerview.adapters;


import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidmkab.recyclerview.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

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





    private OnItemClickListener mOnItemClickListener;
    // Declare Variables
    private Context ctx;
    private List<Integer> items = new ArrayList<>();
    private final int VIEW_ITEM = 2;
    public SharedPreferences.Editor editor;
    public SharedPreferences sharedPreferences;
    String[] titlesAdapter;
    int imagesAdapter[];




    public interface OnItemClickListener {
        void onItemClick(View view, Integer obj, int position);
    }

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mOnItemClickListener = mItemClickListener;
    }

    public AdapterRecyclerView(Context context, String[] titles, int images[]) {
        this.ctx = context;
        this.titlesAdapter = titles;
        this.imagesAdapter = images;

    }




    public class OriginalViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public ImageView thumb;
        public RelativeLayout lyt_parent;
        public TextView tvTitle;

        public OriginalViewHolder(View v) {
            super(v);
            thumb = v.findViewById(R.id.thumb);
            lyt_parent = v.findViewById(R.id.lyt_parent);
            tvTitle = v.findViewById(R.id.tvTitle);

        }
    }

    @Override
    public int getItemViewType(int position) {


        return VIEW_ITEM;

    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder vh;

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_home, parent, false);
        vh = new OriginalViewHolder(v);

        return vh;
    }


    // Replace the contents of a view (invoked by the layout manager)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

        if (holder instanceof OriginalViewHolder) {
            OriginalViewHolder vItem = (OriginalViewHolder) holder;



            // Applying data to Thumbs & TextViews
            vItem.tvTitle.setText(titlesAdapter[position]);
            vItem.thumb.setBackgroundDrawable(ctx.getDrawable(imagesAdapter[position]));

            // Adding onClick Listners to individual Views
            vItem.tvTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Toast.makeText(ctx, "You clicked on Text", Toast.LENGTH_SHORT).show();
                }
            });

            vItem.thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(ctx, "You clicked on Image", Toast.LENGTH_SHORT).show();
                }
            });





            //  Passing OnItemClick listner to Main Activity to handle clicks there
            vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

            

                    //  Toast.makeText(ctx, "working", Toast.LENGTH_SHORT).show();
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(v, items.get(position), position);


                    }
                }
            });

        }



    }

    @Override
    public int getItemCount() {
        Integer[] count = new Integer[imagesAdapter.length];
        items = Arrays.asList(count);
        return items.size();
    }




}

Next Call this Adapter and set it to your recyclerview in your MaintActivity .java file in onCreate method

   // Create Adapter for RecyclerView
        AdapterRecyclerView rvAdapter = new AdapterRecyclerView(MainActivity.this, titles, images);

        //Attach Adapter for RecyclerView
        recyclerView.setAdapter(rvAdapter);


        // OnclickListener for RecyclerVIew
        rvAdapter.setOnItemClickListener(new AdapterRecyclerView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Integer obj, int position) {

                Toast.makeText(MainActivity.this, "You Clicked on " + titles[position], Toast.LENGTH_SHORT).show();


            }
        });

Watch Below Video for better understanding or scroll down to download source code

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn