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 CardView And SQLite example

SQLite Database Android provides several options to save persistent application data. SQlite database is ideal for saving repeating and structured data . Using Sqlite we can save structured data in a private database.  This is a simple application showing use of Sqlite database in android . This example shows how to perform Insert , select , update and delete operation in  SQlite database Screenshots of our sample application                                                                                                                      This is a Registration app. New user can register by clicking registration button . Registered  users are shown in cards below that button . we can update or delete registered users by clicking overflow menu in each card. 1.First we need to create database for our application .    a. Create a contract class .Contract class contains constants that defines names of Tables and columns of our database. Contract class allows us

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path.) 2 . we need to add this bin directory

Google Sign-in for Android App

This is demo application implementing Google Sign-in in android application. Screenshots of the application are when you click on the sign in button popup will be shown to select google account for sign in . After signing in , user can see his profile photo,name and Email id in the login screen . User can sign out using signout button . Disconnect button will provide user ability to disconnect their google account from the app. Before we start coding for our application , we need to turn on sign-in API for our app in google developer console. Go to this link to know  how to turn on google sign-in api for our app https://androidtuts4u.blogspot.com/2019/09/enabling-sign-in-api-in-google.html now we successfully configured Google Api console project .  we can start coding our application. I . first we need to configure build.gradle file we need to add two dependencies   1. google play service dependency for google sign-in.    2 . we are using third party library