Skip to main content

Android Card View And RecyclerView Example

CardView
Cardview lets you show information inside cards that have consistent look across the platform . CardView is introduced with material design through support v7 library. CardView extends frame layout and It can have shadows and round corners.
    Cards can be used as independent views that serves as an entry point to more detailed information. CardView can also  be used with RecyclerView to display cards as list. In this example we are using Cardview with Recyclerview to show data as list of cards.

Our Demo application contains vertical list of cards . Each card contain Movie name, movie poster and director name.
screenshot of demo app



1. CardView and RecyclerView are supportV7 library widget . so we need to add dependency for both in app level build.gradle file . which is in the app folder
 compile 'com.android.support:cardview-v7:26.+'
 compile 'com.android.support:recyclerview-v7:26.+'
build.gradle file is
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.androidtuts4u.arun.democardview"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:cardview-v7:26.+'
    compile 'com.android.support:recyclerview-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    testCompile 'junit:junit:4.12'
}


2.Next we need to create layout for our application . We only need RecyclerView in our main layout . Add the following RecyclerView widget in activity_main.xml
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_movies"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>


activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<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="com.androidtuts4u.arun.democardview.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_movies"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>


3. Next we need to create layout for each row in RecyclerView. Our each row is a card. So we need to create a Cardview . Inside the cardview we need one ImageView for showing movie poster and two  TextView for movie name and director name. 
list_item.xml file is
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="2dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"> 

       <ImageView
            android:id="@+id/iv_poster"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/sr" />

      <TextView
            android:id="@+id/cv_text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Movie Name"
            android:textStyle="bold"
            app:layout_constraintLeft_toRightOf="@+id/iv_poster"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/cv_text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="director name"
            app:layout_constraintLeft_toRightOf="@+id/iv_poster"
            app:layout_constraintTop_toBottomOf="@+id/cv_text1" />

    </android.support.constraint.ConstraintLayout>

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

4. Layouts for our application is finished , now we need to write java classes. We are using Custom adapter for our RecyclerView . So  First we need a model class for creating custom adapter.

5. Model class consist of getter and setter methods. our model class

Movies.java 
package com.androidtuts4u.arun.democardview.model;

public class Movies {
    private int imgID;
    private String movieName, director;
    public int getImgID() {
        return imgID;
    }
    public void setImgID(int imgID) {
        this.imgID = imgID;
    }
    public String getMovieName() {
        return movieName;
    }
    public void setMovieName(String movieName) {
        this.movieName = movieName;
    }
    public String getDirector() {
        return director;
    }
    public void setDirector(String director) {
        this.director = director;
    }
}


6.Next we need to write our adapter class 

MovieAdapter.java
sspackage com.androidtuts4u.arun.democardview.adapter;

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 com.androidtuts4u.arun.democardview.R;
import com.androidtuts4u.arun.democardview.model.Movies;
import java.util.List;

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
    List<Movies> moviesList;
    public MovieAdapter(List<Movies> moviesList) {
        this.moviesList = moviesList;
    }
    @Override
    public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.list_item, parent, false);
        MovieViewHolder viewHolder = new MovieViewHolder(itemView);
        return viewHolder;
    }
    @Override
    public void onBindViewHolder(MovieViewHolder holder, int position) {

        Movies movies = moviesList.get(position);
        holder.movieName.setText(movies.getMovieName());
        holder.director.setText(movies.getDirector());
        holder.ivPoster.setImageResource(movies.getImgID());
    }
    @Override
    public int getItemCount() {
        return moviesList.size();
    }
    public class MovieViewHolder extends RecyclerView.ViewHolder {
        public TextView movieName, director;
        public ImageView ivPoster;
        public MovieViewHolder(View itemView) {
            super(itemView);
            movieName = (TextView) itemView.findViewById(R.id.cv_text1);
            director = (TextView) itemView.findViewById(R.id.cv_text2);
            ivPoster = (ImageView) itemView.findViewById(R.id.iv_poster);
        }
    }
} 

7. Next our MainActivity
MainActivity.java
package com.androidtuts4u.arun.democardview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.androidtuts4u.arun.democardview.adapter.MovieAdapter;
import com.androidtuts4u.arun.democardview.model.Movies;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView movieRecyclerView;
    private RecyclerView.Adapter movieAdapter;
    private RecyclerView.LayoutManager layoutManager;
    List<Movies> moviesList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createMovieList();
        movieRecyclerView = (RecyclerView) findViewById(R.id.rv_movies);
        layoutManager = new LinearLayoutManager(this);
        movieAdapter = new MovieAdapter(moviesList);
        movieRecyclerView.setLayoutManager(layoutManager);
        movieRecyclerView.setAdapter(movieAdapter);
    }
    private void createMovieList() {
        moviesList = new ArrayList<Movies>();
        Movies movieListItem = new Movies();
        movieListItem.setMovieName("Shawshank Redemption");
        movieListItem.setDirector("Frank Darabont");
        movieListItem.setImgID(R.drawable.sr);
        moviesList.add(movieListItem);
        Movies movieListItem1 = new Movies();
        movieListItem1.setMovieName("Forrest Gump");
        movieListItem1.setDirector("Robert Zemeckis");
        movieListItem1.setImgID(R.drawable.fg);
        moviesList.add(movieListItem1);
        Movies movieListItem2 = new Movies();
        movieListItem2.setMovieName("Pulp Fiction");
        movieListItem2.setDirector("Quentin Tarantino");
        movieListItem2.setImgID(R.drawable.pf);
        moviesList.add(movieListItem2);
        Movies movieListItem3 = new Movies();
        movieListItem3.setMovieName("Saving private Ryan");
        movieListItem3.setDirector("Steven Spielberg");
        movieListItem3.setImgID(R.drawable.sp);
        moviesList.add(movieListItem3);
        Movies movieListItem4 = new Movies();
        movieListItem4.setMovieName("Django Unchained");
        movieListItem4.setDirector("Quentin Tarantino");
        movieListItem4.setImgID(R.drawable.du);
        moviesList.add(movieListItem4);
        Movies movieListItem5 = new Movies();
        movieListItem5.setMovieName("The Dark knight");
        movieListItem5.setDirector("Christopher Nolan");
        movieListItem5.setImgID(R.drawable.dn);
        moviesList.add(movieListItem5);
        Movies movieListItem6 = new Movies();
        movieListItem6.setMovieName("The Godfather");
        movieListItem6.setDirector("Francis Ford coppola");
        movieListItem6.setImgID(R.drawable.gf);
        moviesList.add(movieListItem6);
        Movies movieListItem7 = new Movies();
        movieListItem7.setMovieName("The Silence of the Lambs");
        movieListItem7.setDirector("Jonnathan Demme");
        movieListItem7.setImgID(R.drawable.sl);
        moviesList.add(movieListItem7);
        Log.v("listsize main", String.valueOf(moviesList.size()));
    }
}


  • We are not using database in our application , an Arraylist is used for providing static data . Arraylist is created with movie name, director name and image id . Images are saved in the Drawable folder . This Arraylist is passed to our adapter.
private void createMovieList() {
        moviesList = new ArrayList&lt;Movies&gt;();
        Movies movieListItem = new Movies();
        movieListItem.setMovieName("Shawshank Redemption");
        movieListItem.setDirector("Frank Darabont");
        movieListItem.setImgID(R.drawable.sr);
        moviesList.add(movieListItem);
        Movies movieListItem1 = new Movies();
        movieListItem1.setMovieName("Forrest Gump");
        movieListItem1.setDirector("Robert Zemeckis");
        movieListItem1.setImgID(R.drawable.fg);
        moviesList.add(movieListItem1);
        Movies movieListItem2 = new Movies();
        movieListItem2.setMovieName("Pulp Fiction");
        movieListItem2.setDirector("Quentin Tarantino");
        movieListItem2.setImgID(R.drawable.pf);
        moviesList.add(movieListItem2);
        Movies movieListItem3 = new Movies();
        movieListItem3.setMovieName("Saving private Ryan");
        movieListItem3.setDirector("Steven Spielberg");
        movieListItem3.setImgID(R.drawable.sp);
        moviesList.add(movieListItem3);
        Movies movieListItem4 = new Movies();
        movieListItem4.setMovieName("Django Unchained");
        movieListItem4.setDirector("Quentin Tarantino");
        movieListItem4.setImgID(R.drawable.du);
        moviesList.add(movieListItem4);
        Movies movieListItem5 = new Movies();
        movieListItem5.setMovieName("The Dark knight");
        movieListItem5.setDirector("Christopher Nolan");
        movieListItem5.setImgID(R.drawable.dn);
        moviesList.add(movieListItem5);
        Movies movieListItem6 = new Movies();
        movieListItem6.setMovieName("The Godfather");
        movieListItem6.setDirector("Francis Ford coppola");
        movieListItem6.setImgID(R.drawable.gf);
        moviesList.add(movieListItem6);
        Movies movieListItem7 = new Movies();
        movieListItem7.setMovieName("The Silence of the Lambs");
        movieListItem7.setDirector("Jonnathan Demme");
        movieListItem7.setImgID(R.drawable.sl);
        moviesList.add(movieListItem7);
        Log.v("listsize main", String.valueOf(moviesList.size()));
    }

  • We can use Linear Layout Manager , Grid Layout Manager or Staggered Grid Layout Manager for our RecyclerView . In this demo application we are using LinearLayoutManager
        movieRecyclerView = (RecyclerView) findViewById(R.id.rv_movies);
        layoutManager = new LinearLayoutManager(this);
        movieAdapter = new MovieAdapter(moviesList);
        movieRecyclerView.setLayoutManager(layoutManager);
        movieRecyclerView.setAdapter(movieAdapter);

  • list_item.xml file is inflated to RecyclerView in the MovieAdapter class inside onCreateVieHolder method
@Override
    public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.list_item, parent, false);
        MovieViewHolder viewHolder = new MovieViewHolder(itemView);
        return viewHolder;
    }

  • Inside onBindViewHolder method in MovieAdapter class movie name , director name and Image id from Arraylist is set to Each Row.
@Override
    public void onBindViewHolder(MovieViewHolder holder, int position) {

        Movies movies = moviesList.get(position);
        holder.movieName.setText(movies.getMovieName());
        holder.director.setText(movies.getDirector());
        holder.ivPoster.setImageResource(movies.getImgID());
    }

  • TextViews and ImageView of our list_item.xml is declared in the MovieViewHoder class which is a sub class of MovieAdapter clasds
public class MovieViewHolder extends RecyclerView.ViewHolder {
        public TextView movieName, director;
        public ImageView ivPoster;
        public MovieViewHolder(View itemView) {
            super(itemView);
            movieName = (TextView) itemView.findViewById(R.id.cv_text1);
            director = (TextView) itemView.findViewById(R.id.cv_text2);
            ivPoster = (ImageView) itemView.findViewById(R.id.iv_poster);
        }
Full Source code of this Demo application can be downloaded  from the following Googe Drive link 

https://drive.google.com/file/d/0BySLpWhqmbbdVU1rLWsyaUF5c2M/view?usp=sharing


Comments

Popular posts

Android Sqlite and ListView Example

This is simple application which insert data into Sqlite database --and shows the data  from the database in a ListView ListView is not used in android Anymore . We use RecyclerView and CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with CardView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html This  is the first Activity of application which shows data from database in listview. Register here buton will start a Registration Activity. Submit button will add data to database and show it in the ListView of MainActivity. Update can be performed by clicking ListView items.     you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdS0dtT1R2TXdBWEE&usp=sharing click on the above link ->sign into  your  google acc

Android RecyclerView Example

RecyclerView RecyclerView is the advanced version of Listview . It has more flexibility than ListView . RecyclerView is Compatible with Api level 7 onward . We need an adpater class and layout manager for creating Recyclerview.  RecyclerView has 3 built in layout managers LinearlayoutManager - this shows items in vertical or horizontal list GridLayoutManger - this shows item in a grid StaggeredGridLayout Manager - this shows item in a staggered grid we can also create custom layout mangers by extending RecyclerView.LayoutManager class RecyclerView does not have a divider to separate ts iitems . if we want divider we need to extend ItemDecoration class to display the divider RecyclerView also does not have an onItemClickListener for onClick events so we need a class extending RecyclerView.OnItemTouchListener for onclick events or we can use onlick listener in our adapter class we use LinearLayoutManager and a custom Adapter class in this example . This Demo app does no