Browse By

How to Use RecyclerView with CardView in Android application

How to Use RecyclerView with CardView in Android applicationThe RecyclerView widget is a more advanced and flexible version of List View. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. RecyclerView provides LinearLayoutManager, which can show the list of items in either horizontal or vertical pattern.

The CardView UI component shows information inside cards. We can customize its corners, elevation and so on.

In this tutorial we will create an android application using RecyclerView and CardView.

Direct Download Full Source Code

 

 

How to Use RecyclerView with CardView in Android application

To achieve this, you have to add following in build.gradle

compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'
compile 'com.android.support:design:22.2.0'
 

1. RecyclerView is very similar to the ListView and we can use them in the same way.
In activity_main layout, we will define Recyclerview widget.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MyActivity">
    <include layout="@layout/toolbar" />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/cardList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="300dp" />
</LinearLayout>

2. In list view as we define row view, in the same way, we define our row view in Card view. Create layout file card_view.xml in resources/layout.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    card_view:cardPreventCornerOverlap="false"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="2dp"
    card_view:contentPadding="10dp">

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/rel"
        >
        <ImageView
            android:id="@+id/cardimage"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="fitCenter"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="title"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="20sp"
            android:id="@+id/cardtitle"
            android:layout_gravity="center_vertical"
            />
    </LinearLayout>
</android.support.v7.widget.CardView>

3. Now create the model class called Flower.java and create the constructor of Flower class.

package com.vrs.recyclerviewdemo;
/**
 * Created by vrs on 7/10/15.
 */
public class Flower {
    String name;
    int id;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Flower(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

4. Now we have to create adapter class to hold the view. So, create CardAdapter.java class. Recyclerview has two override methods:

a) onCreateViewHolder: Inflate row view in this method

b) onBindViewHolder: Bind the view in this method (equivalent to getview method of listview)

CardAdapter  must extend a class called, RecyclerView.Adapter  passing our class that implements the ViewHolder pattern.

Implements it as below:

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> 
{
public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView cardimage;
    TextView cardtitle;
    Flower Flower;
    public ViewHolder(View itemView) {
        super(itemView);
        cardimage = (ImageView) itemView.findViewById(R.id.cardimage);
        cardtitle = (TextView) itemView.findViewById(R.id.cardtitle);
    }
}


5. Now implement override methods OnCreateViewHolder, OnBindViewHolder and getItemCount method.

6. In onCreateViewHolder inflate our layout file card_view.

@Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, parent, false);
        return new ViewHolder(itemView);
    }

7. In onBindViewHolder, set text and image resource.

@Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.Flower=getItem(position);
        holder.cardtitle.setText(list.get(position).name);
        holder.cardimage.setImageResource(list.get(position).id);
    }

8. Create constructor of CardAdapter class containing context and list.

public CardAdapter(Context mContext, List<Flower> list) {
        this.mContext = mContext;
        this.list = list;
    }

9. So, Final code will look like as follows:

package com.vrs.recyclerviewdemo;
import android.content.Context;
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 java.util.ArrayList;
import java.util.List;
/**
 * Created by vrs on 3/9/15.
 */
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

    List<Flower> list = new ArrayList<>();
    public CardAdapter(List<Flower> list) {
        this.list = list;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, parent, false);
        return new ViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.Flower=getItem(position);
        holder.cardtitle.setText(list.get(position).name);
        holder.cardimage.setImageResource(list.get(position).id);
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
    @Override
    public int getItemCount() {
        return list.size();
    }
    public Flower getItem(int i) {
        return list.get(i);
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView cardimage;
        TextView cardtitle;
        Flower Flower;
        public ViewHolder(View itemView) {
            super(itemView);
            cardimage = (ImageView) itemView.findViewById(R.id.cardimage);
            cardtitle = (TextView) itemView.findViewById(R.id.cardtitle);
        }
    }

10. Now in MainActivity class set it’s contentview as activity_main. Create method “initializeData()” which will contain array list of flowers  and call the constructor of Flower class. Set title and image into it. Call this method before setting adapter.

package com.vrs.recyclerviewdemo;
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 android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    CardAdapter adapter;
    List<Flower> flowers;
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
       LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(llm);
         recyclerView.setHasFixedSize(true);
         initializeData();
        adapter = new CardAdapter(flowers);
        recyclerView.setAdapter(adapter);
    }
    private void initializeData() {
        flowers = new ArrayList<>();
        flowers.add(new Flower("Flower 1", R.drawable.image2));
        flowers.add(new Flower("Flower 2", R.drawable.images3));
        flowers.add(new Flower("Flower 3", R.drawable.images4));
        flowers.add(new Flower("Flower 4", R.drawable.images6));
        flowers.add(new Flower("Flower 5", R.drawable.images7));
        flowers.add(new Flower("Flower 6", R.drawable.images10));
        flowers.add(new Flower("Flower 7", R.drawable.images11));
        flowers.add(new Flower("Flower 8", R.drawable.images12));
        flowers.add(new Flower("Flower 9", R.drawable.images14));
        flowers.add(new Flower("Flower 10", R.drawable.images17));
        flowers.add(new Flower("Flower 11", R.drawable.images18));
        flowers.add(new Flower("Flower 12", R.drawable.index));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

11. Now execute application

I hope you like this article. Share your views to to improve content. Happy Coding !!!

Download Full Source Code