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

How to Open Android Emulator form Command Line and install Apk in Emulator

  You can also view this on my youtube channel How to Open Android Emulator from Commad Line 1.Open Command line 2.Change working directory to android sdk directory    cd  appdata/local/android/sdk/emulator 3.List all available Android virtual devices     emulator -list-avds 4. All your avds will be shown choose the avd_name you want to open    emulator -avd avd_name   5.Your Android virtual device will open up How to install APk file to emulator Drag the APK to Android emulator it will install automatically

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 abov...

ViewModel with Jetpack Compose

  Compose uses remember API to store object in memory. Stored value is returned during recomposition . remember helps us retain data across recompostion , but when configuration changes happen all stored values are lost . One way to overcome this is to use rememberSaveable . rememberSaveable saves any value that can be saved in a Bundle , so it will survive configuration changes.  But when we are using lot of data , for example a list we can cannot use a rememberSavble beacuse there is limit on amount of data that can be stored in Bundle . So we use ViweModel . ViewModel provide the ui state and access to the business logic located in other layers of the app. It also survives configuration changes. ViewModel handles events coming from the UI or other layers of the app and updates the state holder based on the events. We need to add the following dependency in our app level build.gradle to use ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1" F...