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

Simple Calculator in Android

You can view new updated simple calculator with ViemModel and LiveData in my new blog    https://androidtuts4u.blogspot.com/2021/10/simple-calculator-with-viewmodel-and.html To create a calculator first  we need to create the layout of the calculator. Layout  is created  using XML file given below <RelativeLayout 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" >  <EditText     android:id="@+id/result_id"       android:layout_width="fill_parent"     android:layout_height="120dp"   />  <Button    android:id="@+id/Btn7_id"      android:layout_width="70dp"    android:layout_height="60dp"    android:layout_below="@id/result_id"   ...

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

Android External database : Using database in "assets" folder

The best way to create a database application in android is , using an exteranal database . ie, we can create database  using tools like N avicat  , SQLite Browser  and copy this database into our application .This  method is more flexible and easy than creating a database in our application . This is a simple application using external database file.Application will insert data into database and show data from the database in a customized list view.  Screenshots of this application are MainActivity This is the first activity of this application . When  Register Here button is pressed it will start Registration Activity Editing of the entries can be done with a Long Click on the listView items. you can download the source code of this project from  google drive  https://drive.google.com/folderview?id=0BySLpWhqmbbdY3JHMkZRZFN0bEE&usp=sharing click on the above link ->sign into  your  google account ->a...