Android RecyclerView With CardView

By | November 8, 2015

In this previous series we have seen tutorial on how to create RecyclerView with scrolling behaviour and also on how to create CardView and it’s customization . As the title of this post suggest in this tutorial we will see the combination of this two widget.

androoidrecyclerviewcardview

Build Gradle

Add the following lines to the dependencies section in your project’s build.grade file and sync .It include design support library , recyclerView library and cardview library .

file : build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.android.support:cardview-v7:23.0.1'
    compile 'com.android.support:recyclerview-v7:23.0.1'
    }

String Constant

Before i start coding I have initialize all the necessary string-array constant inside res/strings.xml and i also kept all the necessary images inside the drawable folder of the project .

file : strings.xml

<resources>

    <string name="app_name">RecycleViewDemo</string>
    <string name="action_settings">Settings</string>

    <!–- Names -–>

    <string-array name="names">

        <item>Pavan D</item>
        <item>DayaSagar</item>
        <item>Pavan B</item>
        <item>Maddy</item>
        <item>Pavan H</item>
        <item>Nikhil</item>
        
    </string-array>

    <!–- Pictures -–>

    <array name="profile_pics">

        <item>@drawable/pavand_pic</item>
        <item>@drawable/daya_pic</item>
        <item>@drawable/pavanb_pic</item>
        <item>@drawable/maddy_pic</item>
        <item>@drawable/pavanh_pic</item>
        <item>@drawable/nikhil_pic</item>

    </array>

    <!–- Email -–>

    <string-array name="email">

        <item>hdpavan@xyz.com</item>
        <item>daya@xyz.com</item>
        <item>pavanb@xyz.com</item>
        <item>maddy@xyz.com</item>
        <item>pavanh@xyz.com</item>
        <item>nikhil@xyz.com</item>
    </string-array>

</resources>

XML Layout

Create XML layout file in res/layout and name it activity_main.xml with LinearLayout as a parent view add the toolbar widget inside the appbarlayout and then add recyclerView as to child to linear layout .

file : activity_main.xml

<LinearLayout 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">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

        <android.support.design.widget.CoordinatorLayout
            android:id="@+id/coordinator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways" />

        </android.support.design.widget.CoordinatorLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>

Create a XML Layout inside res/layout and name it cardview_row_item.xml and add cardview to it .In the previous tutorial i have cover on android cardview and it’s customization .

file : cardview_row_item.xml

<?xml version="1.0″ encoding="utf-8″?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">

            <ImageView
                android:id="@+id/profile_pic"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <TextView
                android:id="@+id/member_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/profile_pic"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/member_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/member_name"
                android:layout_toRightOf="@+id/profile_pic" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Java Bean

Create a Bean Class Member which defines the data for items of recyclerview .

file : Member.java

package com.tutorialsbuzz.recycleviewdemo;

public class Member {

    String name;
    String email;
    int photoID;

    Member(String name, String email, int photoID) {
        this.name = name;
        this.email = email;
        this.photoID = photoID;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public int getPhotoID() {
        return photoID;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPhotoID(int photoID) {
        this.photoID = photoID;
    }
}

RecyclerView Adapter

Create a class RVAdapter and extend it to RecyclerView.Adapter<RVAdapter.MemberViewHolder>
RecyclerView.Adapter has three abstract methods that we must override .

  • getItemCount() : This method return the number of items present in the data
  • onCreateViewHolder() : Inside this method we specify the layout that each item of the RecyclerView should use. This is done by inflating the layout using LayoutInflater, passing the output to the constructor of the custom ViewHolder.
  • onBindViewHolder() : This Method This method is very similar to the getView method of a ListView’s adapter. In our example, here’s where you have to set the values of the name, email and photoID data member of Member class to the respective view inside the CardView.

file : RVAdapter.java

package com.tutorialsbuzz.recycleviewdemo;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.MemberViewHolder> {

    private List<Member> members;
    private Context context;

    public RVAdapter(List<Member> members, Context context) {
        this.members = members;
        this.context = context;
    }

    public class MemberViewHolder extends RecyclerView.ViewHolder {

        private CardView cardView;
        private TextView name_tv;
        private TextView email_tv;
        private ImageView pic_iv;

        public MemberViewHolder(View itemView) {
            super(itemView);
            cardView = (CardView) itemView.findViewById(R.id.cv);
            name_tv = (TextView) itemView.findViewById(R.id.member_name);
            email_tv = (TextView) itemView.findViewById(R.id.member_email);
            pic_iv = (ImageView) itemView.findViewById(R.id.profile_pic);
        }
    }

    @Override
    public void onBindViewHolder(MemberViewHolder memberViewHolder, int i) {
        memberViewHolder.name_tv.setText(members.get(i).getName());
        memberViewHolder.email_tv.setText(members.get(i).getEmail());
        memberViewHolder.pic_iv.setImageResource(members.get(i).getPhotoID());
    }

    @Override
    public MemberViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_row_item, viewGroup, false);
        MemberViewHolder memberViewHolder = new MemberViewHolder(view);
        return memberViewHolder;
    }

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

MainActivity

1. Create a class MainActivity and extend it to AppCompatActivity .
2. Inside the onCreate method set the content of this activity with above defined xml layout and then set-up toolbar and also initialize the data member of Member class

Setting LayoutManager .
Unlike a ListView, a RecyclerView needs a LayoutManager to manage the positioning of its items you could simply use one of the predefined LayoutManager subclasses:

  • LinearLayoutManager.
  • GridLayoutManager.
  • StaggeredGridLayoutManager.

In this tutorial, I am going to use a LinearLayoutManager. This LayoutManager subclass by default, make your RecyclerView look like a ListView.

3. Next , call to setAdpter api on recyclerview instance by pass instance of above defined Custom Adapter (RVAdapter).

file : MainActivity.java

package com.tutorialsbuzz.recycleviewdemo;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerview;
    private String[] names;
    private TypedArray profile_pics;
    private String[] emails;
    private List<Member> memberList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        names = getResources().getStringArray(R.array.names);
        profile_pics = getResources().obtainTypedArray(R.array.profile_pics);
        emails = getResources().getStringArray(R.array.email);

        memberList = new ArrayList<Member>();
        for (int i = 0; i < names.length; i++) {
            Member member = new Member(names[i], emails[i], profile_pics.getResourceId(i, -1));
            memberList.add(member);
        }

        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerview.setLayoutManager(layoutManager);
        RVAdapter adapter = new RVAdapter(memberList, MainActivity.this);
        recyclerview.setAdapter(adapter);
    }

}

androoidrecyclerviewwithcardview

androoidrecyclerviewcardviewlandscape

More Tutorial On RecyclerView

  1. RecyclerView With Scrolling Behaviour.
  2. RecyclerView Item Click Listener With Ripple Effect.
  3. RecyclerView Item Filter.
  4. RecyclerView Item Filter With Animation.
  • Thankk you so much for this tutorial. Can you explain onClick item on cardviews. I am looking forward to see onClick item tutorial…

  • @Ahmet
    I have written a tutorials recyclerView Item listener at http://www.tutorialsbuzz.com/2015/12/Android-RecyclerView-Item-Click-Listener-Ripple-Effect.html

  • memberList = new ArrayList();
    for (int i = 0; i < names.length; i++) {
    Member member = new Member(names[i], emails[i], profile_pics.getResourceId(i, -1));
    memberList.add(member);
    }

    recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
    LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
    recyclerview.setLayoutManager(layoutManager);
    RVAdapter adapter = new RVAdapter(memberList, MainActivity.this);
    recyclerview.setAdapter(adapter);

    i get error:
    member is abstract [
    Member member = new Member(names[i], emails[i], profile_pics.getResourceId(i, -1));
    ]

    any idea why?

  • Thanks for the nice tutorial.
    Could you please tell us how to implement the exact same code but for a fragment?
    For example to use in NavigationDrawer Fragment as CardView.
    Thanks!

  • Thanks for the tutorial.
    But could you please do the exact same tutorial but for fragment?
    For example to use NavigationDrawer along with CardView??