Material Design Topics

RecyclerView Tutorial With Example In Android Studio

In Android, RecyclerView is an advanced and flexible version of ListView and GridView. It is a container used for displaying large amount of data sets that can be scrolled very efficiently by maintaining a limited number of views. RecyclerView was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).

RecyclerView in AndroidThis new widget is a big step for displaying data in Material Design because the ListView and GridView are one of the most commonly used UI widget. In RecyclerView android provides a lots of new features which are not present in existing ListView or GridView.

Important Note:

In Android, RecyclerView provides an ability to implement the horizontal, vertical and Expandable List. It is mainly used when we have data collections whose elements can change at run time based on user action or any network events. For using this widget we have to specify the Adapter and Layout Manager.

Basic RecyclerView XML code:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="abhiandroid.com.recyclerviewexample.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

Gradle Dependency to use RecyclerView:

The RecyclerView widget is a part of separate library valid for API 7 level or higher. Add the following dependency in your Gradle build file to use recyclerview.

Gradle Scripts > build.gradle and inside dependencies

dependencies {
...
compile "com.android.support:recyclerview-v7:23.0.1"
}

Need of RecyclerView In Android

RecyclerView uses a ViewHolder for storing the reference of the view for one entry in the RecyclerView. When we use ListView or GridView for displaying custom items then we create a custom xml file and then use it inside our Adapter. For this we create a CustomAdapter class and then extends our Base or any other Adapter in it. In getView() method of our Adapter we inflate the item layout xml file and then give the reference of every view by using the unique id’s we provide in our xml file . Once finished we pass that view to the ListView, ready to be drawn, but the truth is that ListView and GridView do only half the job of achieving true memory efficiency.

ListView/GridView recycle the item layout but don’t keep the reference to the layout children, forcing us to call findViewById() for every child of our item layout for every time we call getView(). This issue causes the scrolling or non responsive problem as it frantically tries to grab references to the view’s we needed.

With the arrival of RecyclerView everything is changed. RecyclerView still uses Adapter to act as Data source but in this we have to create a ViewHolder to keep the reference of View in memory, so when we need a new view it either creates a new ViewHolder object to inflate the layout and hold those references or it recycles one from existing stack.


Components of RecyclerView In Android

Below we define the mainly used components of a RecyclerView.

1. Layout Managers:

In Android a RecyclerView needs to have a Layout Manager and an Adapter to be instantiated. Layout Manager is a very new concept introduced in RecyclerView for defining the type of Layout which RecyclerView should use. It Contains the references for all the views that are filled by the data of the entry. We can create a Custom Layout Manager by extending RecyclerView.LayoutManager Class but RecyclerView Provides three types of in-built Layout Managers.

Linear Layout Manager – It is used for displaying the data items in a horizontal or vertical scrolling List
GridLayoutManager – It is used to show the items in grid format
StaggeredGridLayoutManager – It is used to show the items in staggered Grid.

Below we explain each type in details:

Linear Layout Manager

RecyclerView As ListView In Android Studio
It is used for displaying the data items in a horizontal or vertical scrolling List. If we need a list(vertical or horizontal) then we need to use LinearLayoutManager with require orientation. In Simple words we can say that we use the LinearLayoutManager for displaying RecyclerView as a ListView.

Public constructor for LinearLayoutManager

  • LinearLayoutManager(Context context): It is used to create a vertical LinearLayoutManager. In this we need to set only one parameter i.e used to set the context the current Activity. EExample: In below code snippet we show how to use this constructor in Android.
    With Default Vertical Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a LinearLayoutManager with default orientation
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView
    

    With Horizontal Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a LinearLayoutManager
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); // set Horizontal Orientation
    recyclerView.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView
    
  • LinearLayoutManager(Context context, int orientation, boolean reverseLayout): In this first parameter is used to set the current context, second is used to set the Layout Orientation should be vertical or horizontal. By using this constructor we can easily create a horizontal or vertical List. Third parameter is a boolean value when set to true layouts from end to start it means items are arranged from end to start.
    Example: In below code snippet we show how to use this constructor in Android.

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
    // set a LinearLayoutManager with default horizontal orientation and false value for reverseLayout to show the items from start to end
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false);
    recyclerView.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView
    

For more details read RecyclerView As ListView With Example

GridLayoutManager

RecyclerView as GridView In Android Studio
It is used to show the items in grid format. If we need to display items in grid format then we can use GridLayoutManager. In simple words we can say that we use the GridLayoutManager for displaying RecyclerView as a GridView.
Public constructor for GridLayoutManager:

  • GridLayoutManager (Context context, int spanCount): It is used to create a Vertical GridLayoutManager. In this constructor first parameter is used to set the current context and second parameter is used to set the spanCount means the number of columns in the grid.
    Example: In below code snippet we show how to use this constructor in Android.
    With Default Vertical Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a GridLayoutManager with default vertical orientation and 3 number of columns
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),3);
    recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView

    With Horizontal Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a GridLayoutManager with 3 number of columns
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),3);
    gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); // set Horizontal Orientation
    recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
  • GridLayoutManager (Context context, int spanCount, int orientation, boolean reverseLayout): In this constructor first parameter is used to set the current context, second parameter is used to set the spanCount means the number of columns in the grid, third parameter is used to set the Layout Orientation should be vertical or horizontal and last param is a boolean value when sets to true layout from end to start means grids are arranged from end to start.
    Example: In below code snippet we show how to use this constructor in Android.

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a GridLayoutManager with 3 number of columns , horizontal gravity and false value for reverseLayout to show the items from start to end
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),3,LinearLayoutManager.HORIZONTAL,false);
    recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
    

For more details read RecyclerView Using GridLayoutManager With Example

StaggeredGridLayoutManager

GridView vs Staggered Grid In Android Studio
It is used to show the items in staggered Grid.

Public constructor for StaggeredGridLayoutManager

  • StaggeredGridLayoutManager(int spanCount, int orientation): it is used to create a StaggeredGridLayoutManager with given parameters. First parameter is used to set spanCount means number of columns if orientation is vertical or number of rows if orientation is horizontal, Second Parameter is used to set the Orientation, it should be vertical or horizontal.
    Example: In below code snippet we show how to use this constructor in Android.
    With Vertical Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a StaggeredGridLayoutManager with 3 number of columns and vertical orientation
    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(staggeredGridLayoutManager); // set LayoutManager to RecyclerView
    

    With Horizontal Orientation:

    // get the reference of RecyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    // set a StaggeredGridLayoutManager with 3 number of columns and horizontal orientation
    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);
    recyclerView.setLayoutManager(staggeredGridLayoutManager); // set LayoutManager to RecyclerView

2.ViewHolder: ViewHolder is used to store the reference of the View’s for one entry in the RecyclerView. A ViewHolder is a static inner class in our Adapter which holds references to the relevant view’s. By using these references our code can avoid time consuming findViewById() method to update the widgets with new data.

3. RecyclerView.Adapter:
RecyclerView includes a new kind of Adapter. It’s a similar approach to the ones we already used but with some peculiarities such as a required ViewHolder for handling Views. We will have to override two main methods first one to inflate the view and its viewholder and another one to bind the data to the view. The main good thing in this is that the first method is called only when we really need to create a new view.

In Below code snippet we show how’s our CustomAdapter looks when we extends RecyclerView.Adapter class in it.

package abhiandroid.com.recyclerviewexample;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class CustomAdapter extends RecyclerView.Adapter {
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;// init the item view's
public MyViewHolder(View itemView) {
super(itemView);

// get the reference of item view's
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
}

4. ItemAnimator: RecyclerView.ItemAnimator will animate ViewGroup modification such as delete, select, add that notify the Adapter. DefaultItemAnimator can be used for providing default Animation and it works quite well.

For more details read RecyclerView As Staggered Grid with example


RecyclerView Example In Android Studio:

Below is the example of RecyclerView in which we display the list of Person Names with the help of RecyclerView. In this example we are using LinearLayoutManager with vertical orientation to display the items. Firstly we declare a RecyclerView in our XML file and then get the reference of it in our Activity. After that we creates an ArrayList for Person Names and set a LayoutManager and finally we set the Adapter to show the items in RecyclerView. Whenever a user clicks on an item the name of the Person is displayed on the screen with the help of Toast.

Download Code

RecyclerView Example In Android Studio
Step 1: Create a new Project and name it RecyclerView Example.

Step 2: Open Gradle Scripts > build.gradle and add RecyclerView Library dependency in it.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "abhiandroid.com.recyclerviewexample"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView
}

 

Step 3: Open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this step we create a RecyclerView in our XML file.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="abhiandroid.com.recyclerviewexample.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

Step 4: Create a new XML file rowlayout.xml for item of RecyclerView and paste the following code in it.

In this step we create a new xml file for item row in which we creates a TextView to show the data.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <!--
    items for a single row of RecyclerView
    -->
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="#000"
        android:textSize="20sp" />
</LinearLayout>

 

Step 5 : Now open app -> java -> package -> MainActivity.java and add the below code.

In this step firstly we get the reference of RecyclerView. After that we creates an ArrayList for Person Names and set a LayoutManager and finally we set the Adapter to show the items in RecyclerView.

package abhiandroid.com.recyclerviewexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
    // ArrayList for person names
    ArrayList personNames = new ArrayList<>(Arrays.asList("Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6", "Person 7"));
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the reference of RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        // set a LinearLayoutManager with default vertical orientation
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        //  call the constructor of CustomAdapter to send the reference and data to Adapter
        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, personNames);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
    }
}

Step 6: Create a new class CustomAdapter.java inside package and add the following code.

In this step we create a CustomAdapter class and extends RecyclerView.Adapter class with ViewHolder in it. After that we implement the overrided methods and create a constructor for getting the data from Activity, In this custom Adapter two methods are more important first is onCreateViewHolder in which we inflate the layout item xml and pass it to View Holder and other is onBindViewHolder in which we set the data in the view’s with the help of ViewHolder.

package abhiandroid.com.recyclerviewexample;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter {
    ArrayList personNames;
    Context context;
    public CustomAdapter(Context context, ArrayList personNames) {
        this.context = context;
        this.personNames = personNames;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
        return vh;
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        // set the data in items
        holder.name.setText(personNames.get(position));
        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // display a toast with person name on item click
                Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    public int getItemCount() {
        return personNames.size();
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView name;// init the item view's
        public MyViewHolder(View itemView) {
            super(itemView);
            // get the reference of item view's
            name = (TextView) itemView.findViewById(R.id.name);
        }
    }
}

Output:

Now run the App and you will see different names of person listed in ListView.

For More Example Of RecyclerView Read:

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

Download Free - Master Android App Development Sidebar

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

Android Developer Facebook Group Free

Premium Project Source Code:




Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

See How AbhiAndroid Step By Step Video Training Helps You Master Android App Development

Video Training - Unlock step by step video training with new content added regularly. Develop Android Apps.
Android App Source Code - Get amazing Ecommerce, Food Ordering and Ultimate WebView source code with documentation.
ENROLL NOW
close-link

With a very poor revenue from selling source code files or using Google AdSense, we need your help to survive this website. Please contribute any amount you can afford
Pay
* Terms & Conditions Apply
close-link