Skip to main content

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

  1. LinearlayoutManager - this shows items in vertical or horizontal list
  2. GridLayoutManger - this shows item in a grid
  3. 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 not have divider to separate items in the list and OnclickListener is written in adapter class . 

screenshot of the demo app



Demo app has vertical list of movie names and director and on clicking each item a toast is shown with movie name

1. First we need to add dependencies on build.gradle file which is in the app folder
 add this dependency in build.gradle
compile 'com.android.support:recyclerview-v7:25.1.0'

gradle.build  file is
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.androidtuts4u.arun.demorecyclerview"
        minSdkVersion 16
        targetSdkVersion 25
        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:25.1.0'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:recyclerview-v7:25.1.0'

}

2. Next we need to create  layout for our application .we only need Recyclerview widget  in our main layout .  
<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

activity_main.xml file is
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidtuts4u.arun.demorecyclerview.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

3. Next we need to create custom layout for each Row in the Recyclerview . Our demo application  consist of two texts one movie name and second director name  so each row consists of two TextView

list_item.xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_movie"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@android:color/black"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/tv_director"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@android:color/black" />
</LinearLayout>

4. Now  layout for the application is complete . next we need to write the java class. Custom adapter is used in the application , so to create Custom adapter first we need a model class

5. Model class consist of getter and setter methods . model class  
movies .java

package com.androidtuts4u.arun.demorecyclerview.model;
public class Movies {
    String movieName, Director;
    public String getMovieName() {
        return movieName;
    }
    public void setMovieName(String movieName) {
        this.movieName = movieName;
    }
    public String getDirector() {
        return Director;
    }
    public void setDirector(String director) {
        Director = director;
    }
}

6. Next we nee to write custom Adapter class  .Our adapter class is
MovieAdapter.java
package com.androidtuts4u.arun.demorecyclerview.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidtuts4u.arun.demorecyclerview.MainActivity;
import com.androidtuts4u.arun.demorecyclerview.R;
import com.androidtuts4u.arun.demorecyclerview.model.Movies;
import java.util.List;
import java.util.StringTokenizer;

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
    List<Movies> movieList;
    public MovieAdapter(List<Movies> movieList) {
        this.movieList = movieList;
        Log.v("list", movieList.toString());
    }

    @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 = movieList.get(position);
        holder.movieName.setText(movies.getMovieName());
        holder.director.setText(movies.getDirector());
        holder.seListners(position);
    }
    @Override
    public int getItemCount() {
        Log.v("listsize adapter", String.valueOf(movieList.size()));
        return movieList.size();
    }
    public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView movieName, director;
        LinearLayout item;
        int position;
        public MovieViewHolder(View itemView) {
            super(itemView);
            item = (LinearLayout) itemView.findViewById(R.id.item);
            movieName = (TextView) itemView.findViewById(R.id.tv_movie);
            director = (TextView) itemView.findViewById(R.id.tv_director);
        }
        @Override
        public void onClick(View view) {
            Movies movies = movieList.get(position);
            String movieName = movies.getMovieName();
            Toast.makeText(view.getContext(), movieName, Toast.LENGTH_LONG).show();
        }
        public void seListners(int position) {
            this.position = position;
            item.setOnClickListener(MovieViewHolder.this);
        }
    }
}

7.Next our MainActivity
ManiActivity.java
package com.androidtuts4u.arun.demorecyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.androidtuts4u.arun.demorecyclerview.adapter.MovieAdapter;
import com.androidtuts4u.arun.demorecyclerview.model.Movies;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    RecyclerView movieRecyclerView;
    RecyclerView.Adapter recyclerAdapter;
    RecyclerView.LayoutManager recyclermanager;
    List<Movies> moviesList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        movieRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclermanager = new LinearLayoutManager(this);
        movieRecyclerView.setLayoutManager(recyclermanager);
        createMovieList();
        recyclerAdapter = new MovieAdapter(moviesList);
        movieRecyclerView.setAdapter(recyclerAdapter);
    }
    private void createMovieList() {

        moviesList = new ArrayList<Movies>();
        Movies movieListItem = new Movies();
        movieListItem.setMovieName("Shawshank Redemption");
        movieListItem.setDirector("Frank Darabont");
        moviesList.add(movieListItem);
        Movies movieListItem1 = new Movies();
        movieListItem1.setMovieName("Forrest Gump");
        movieListItem1.setDirector("Robert Zemeckis");
        moviesList.add(movieListItem1);
        Movies movieListItem2 = new Movies();
        movieListItem2.setMovieName("Pulp Fiction");
        movieListItem2.setDirector("Quentin Tarantino");
        moviesList.add(movieListItem2);
        Movies movieListItem3 = new Movies();
        movieListItem3.setMovieName("Saving private Ryan");
        movieListItem3.setDirector("Steven Spielberg");
        moviesList.add(movieListItem3);
        Movies movieListItem4 = new Movies();
        movieListItem4.setMovieName("Django Unchained");
        movieListItem4.setDirector("Quentin Tarantino");
        moviesList.add(movieListItem4);
        Movies movieListItem5 = new Movies();
        movieListItem5.setMovieName("The Dark knight");
        movieListItem5.setDirector("Christopher Nolan");
        moviesList.add(movieListItem5);
        Movies movieListItem6 = new Movies();
        movieListItem6.setMovieName("The Godfather");
        movieListItem6.setDirector("Francis Ford coppola");
        moviesList.add(movieListItem6);
        Movies movieListItem7 = new Movies();
        movieListItem7.setMovieName("The Silence of the Lambs");
        movieListItem7.setDirector("Jonnathan Demme");
        moviesList.add(movieListItem7);
        Log.v("listsize main", String.valueOf(moviesList.size()));
    }
}

  • We are not using Database in our application . So we created an Arraylist consisting of movie name and director name and the Arraylist is passed  to our adapter . Arraylist is created in the MainActivity.java
 private void createMovieList() {
        moviesList = new ArrayList<Movies>();
        Movies movieListItem = new Movies();
        movieListItem.setMovieName("Shawshank Redemption");
        movieListItem.setDirector("Frank Darabont");
        moviesList.add(movieListItem);
        Movies movieListItem1 = new Movies();
        movieListItem1.setMovieName("Forrest Gump");
        movieListItem1.setDirector("Robert Zemeckis");
        moviesList.add(movieListItem1);
        Movies movieListItem2 = new Movies();
        movieListItem2.setMovieName("Pulp Fiction");
        movieListItem2.setDirector("Quentin Tarantino");
        moviesList.add(movieListItem2);
        Movies movieListItem3 = new Movies();
        movieListItem3.setMovieName("Saving private Ryan");
        movieListItem3.setDirector("Steven Spielberg");
        moviesList.add(movieListItem3);
        Movies movieListItem4 = new Movies();
        movieListItem4.setMovieName("Django Unchained");
        movieListItem4.setDirector("Quentin Tarantino");
        moviesList.add(movieListItem4);
        Movies movieListItem5 = new Movies();
        movieListItem5.setMovieName("The Dark knight");
        movieListItem5.setDirector("Christopher Nolan");
        moviesList.add(movieListItem5);
        Movies movieListItem6 = new Movies();
        movieListItem6.setMovieName("The Godfather");
        movieListItem6.setDirector("Francis Ford coppola");
        moviesList.add(movieListItem6);
        Movies movieListItem7 = new Movies();
        movieListItem7.setMovieName("The Silence of the Lambs");
        movieListItem7.setDirector("Jonnathan Demme");
        moviesList.add(movieListItem7);
        Log.v("listsize main", String.valueOf(moviesList.size()));
    }
  • list_tem.xml is inflated to our RecyclerView in the Adapter Class MovieAdapter.java 
1@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.java Movie name and Director name from the Arraylist is set to each row
    public void onBindViewHolder(MovieViewHolder holder, int position) {
        Movies movies = movieList.get(position);
        holder.movieName.setText(movies.getMovieName());
        holder.director.setText(movies.getDirector());
        holder.seListners(position);
    }
  • OnClickListener for the Recyclerview is written inside the MovieAdapter.java
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView movieName, director;
        LinearLayout item;
        int position;
        public MovieViewHolder(View itemView) {
            super(itemView);
            item = (LinearLayout) itemView.findViewById(R.id.item);
            movieName = (TextView) itemView.findViewById(R.id.tv_movie);
            director = (TextView) itemView.findViewById(R.id.tv_director);
        }
        @Override
        public void onClick(View view) {
            Movies movies = movieList.get(position);
            String movieName = movies.getMovieName();
            Toast.makeText(view.getContext(), movieName, Toast.LENGTH_LONG).show();
        }
        public void seListners(int position) {
            this.position = position;
            item.setOnClickListener(MovieViewHolder.this);
        }
 
You can Dowload the Full Demo Project from the following Drive link

https://drive.google.com/file/d/0BySLpWhqmbbdQnI0VFpCem5hb1k/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 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.applicat