Android RecyclerView


Android RecyclerView Tutorial and Examples

This is an android recyclerview tutorial. We see what a recyclerview is, why we need it and several examples of how to apply it.

What is a RecyclerView?

A RecyclerView is an adapterview that allows us display a large data set through just a limited window.

RecyclerViews were introduced in Android API 5 as an alternative to ListViews. ListView as you may already know is also an adapterview and allows us display items in a vertically scrolling list.

The term RecyclerView comes from a combination of two words: Recycler and View.

The term Recycler comes from the verb recycle which means to treat things that have already been used so that they can be used again if Oxford Advanced Learner's Dictionary* is to be believed.

Collins Cobuild English Dictionary tells us that a view refers to the way in which a piece of text or graphics is displayed on a computer screen.

And to be honest those two terms in a way defines us exactly what a RecyclerView is. In that a RecyclerView recycles views. It reuses views. And those views are just pieces of grahpical user interface widgets that normally we define in XML and get inflated in java.

RecyclerViews are not limited to any one particular view. Instead it can utilize any. Be it TextViews, Buttons, checkBoxes etc.

RecyclerView is meant to work as an adapterview, basically with an adapter that adapts data to the RecyclerView's views. AdapterViews normally display collections of data.

Even though there have been various great and popular adapterviews like ListViews, GridViews and expandablelistviews, recyclerview is the best when it comes to displaying large quantities of data.

And that's because of it's concept of recycling already used views instead of re-inflating them everytime.

Infation of views is normally expensive as it involves parsing of XML layouts into java objects. And remember this is to be done in realtime as the user scrolls through a list of data. Users can definitely notice that. And you can imagine having hundreds of rows or grids of data. Not so good isn't it?

So RecyclerView is great in this regard as instead of re-inflating the views, it holds them in a ViewHolder class and then recycles them, only binding fresh data to them. The end result is smoothness even with large datasets that we and our users can take for granted.

Advantages of RecyclerViews
No. Advantage Description
1. Efficient. Android Engineers introduced RecyclerViews to provide a more efficient way of displaying large data sets. Previously ListViews were and gridviews were the only inbuilt alternatives. They are great for small data sets but not for large.
2. Flexible RecyclerViews are the most flexible adapterviews in android. I have seen people using them to build almost anything from creating input forms to scrollable grids to other adapterviews.
3. Easy to use. This is one of the reasons why they are popular. Some may argue that you always need two or three classes however, these are simple classes that can be combined in one file.
4. Obeys SOC(Seperation of Concerns) A RecyclerView decouples adapter from views. Hence we can work on either without touching the other.
Programmatic Definition of RecyclerViews

Like anything you can imagine in android or even java at large, a RecyclerView is just a class:

class RecyclerView{..} 

This clas is defined in a package:

package android.support.v7.widget;

And is public so that it's not only visible to class in this package but also those in other packages:

public class RecyclerView{..} 

RecyclerView extends android.view.ViewGroup. ViewGroup is a special view that can contain other views. It can basically hold children within itself. Think of views like relativelayout and linearlayout.

public class RecyclerView extends ViewGroup... {..}

This will give a RecyclerView the capability to hold views as well.

Then RecyclerView implements two interfaces:

public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild{..}
  1. ScrollingView - An interface housed in the android.support.v4.view package. It provides scroll related APIs to RecyclerView. These includes APIs such as computeHorizontalScrollExtent(),computeVerticalScrollExtent() etc.

  2. NestedScrollingChild - Also belongs to android.support.v4.view and provides support for dispatching of nested scrolling operations to a cooperating parent ViewGroup.

1 : Android RecyclerView - Fill With Array

Android RecyclerView Tutorial - How to fill a recyclerview from an array.

This is a simple RecyclerView tutorial.Here is what we do:

  • Fill RecyclerView with data from a simple Array.
  • We derive from RecycelView.ViewHolder to get our custom viewholder class.
  • We aslo derive from RecyclerView.Adapter to get our adapter class that helps us bind our data to our RecyclerView.
  • We create a model layout using cardview that's inflated to a view item for our recyclerview.

What this Example Teaches Us
  1. How to populate a recyclerview with an array.
  2. How to render cardviews in a recyclerview.
(a). Our View Holder Class
  • Holds our views for recycling.
package com.tutorials.hp.recyclerviewarray;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);

    }

}
(b). Our Adapter Class
  • Responisble for layout inflation.
  • Initializes our View holder.
  • Binds data to our views.
package com.tutorials.hp.recyclerviewarray;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    String[] spacecrafts;

    public MyAdapter(Context c, String[] spacecrafts) {
        this.c = c;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(spacecrafts[position]);

    }

    @Override
    public int getItemCount() {
        return spacecrafts.length;
    }
}
(c) .Our MainActivity
  • Launcher activity.
  • References RecyclerView and sets its layout manager.
  • Instantiates and sets our adapter to RecyclerView.
package com.tutorials.hp.recyclerviewarray;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    String[] spacecrafts={"Juno","Hubble","Casini","WMAP","Spitzer","Pioneer","Columbia","Challenger","Apollo","Curiosity"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv = (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //ADAPTER
        MyAdapter adapter = new MyAdapter(this, spacecrafts);
        rv.setAdapter(adapter);
    }
}
(d). Our Model XML Layout
  • A single cardview in our recyclerview.
  • Shall be inflated to a view item.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="5dp"
    android:layout_height="200dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="10dp"
                android:textColor="@color/colorAccent"
                android:textStyle="bold"
                android:layout_alignParentLeft="true"
                />

</android.support.v7.widget.CardView>

2. Android RecyclerView - Fill With ArrayList

How to populate a recyclerview from an arraylist.

This is a simple RecyclerView and ArrayList tutorial.Here is what we do:

  • Fill RecyclerView with data from a simple ArrayList.
  • We derive from RecycelView.ViewHolder to get our custom viewholder class.
  • We aslo derive from RecyclerView.Adapter to get our adapter class that helps us bind our data to our RecyclerView.
  • We create a model layout using cardview that's inflated to a view item for our recyclerview.

What This Example Teaches
  1. How to fill a recyclerview with an arraylist.
  2. How to show cardviews in a recyclerview.
  3. How to inflate a model layout into an java view item.
(a). Our View Holder Class
  • Holds our views for recycling.
package com.tutorials.hp.recyclerviewlist;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);

    }

}
(b). Our Adapter Class
  • Responisble for layout inflation.
  • Initializes our View holder.
  • Binds data to our views.
package com.tutorials.hp.recyclerviewlist;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<String> numbers;

    public MyAdapter(Context c, ArrayList<String> numbers) {
        this.c = c;
        this.numbers = numbers;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(numbers.get(position));

    }

    @Override
    public int getItemCount() {
        return numbers.size();
    }
}
(c). Our MainActivity
  • Launcher activity.
  • References RecyclerView and sets its layout manager.
  • Instantiates and sets our adapter to RecyclerView.
package com.tutorials.hp.recyclerviewlist;

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;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> numbers=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //SETUP RECYCLER
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //FILL LIST
        fillList();

        //adapter
        MyAdapter adapter=new MyAdapter(this,numbers);
        rv.setAdapter(adapter);

    }

    private void fillList()
    {
        for(int i=0;i<10;i++)
        {
            numbers.add("Number "+String.valueOf(i));
        }

    }
}
(d). Our Model XML Layout
  • A single cardview in our recyclerview.
  • Shall be inflated to a view item.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="5dp"
    android:layout_height="200dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="10dp"
                android:textColor="@color/colorAccent"
                android:textStyle="bold"
                android:layout_alignParentLeft="true"
                />

</android.support.v7.widget.CardView>

3. Android RecyclerView - Fill With List Of Objects

In this tutorial we take a look at how to populate a recyclerView with list of objects.Our recycerview is going to consist of two textviews inside a cardview.

(a). Our build.gradle
  •  Lets add two dependencies,support design and cardview in our buil.gradle(Module:app)
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile 'com.android.support:cardview-v7:24.0.0'
}
(b). Our Model Class
  • Is our data object representing a single Person object.
package com.tutorials.hp.recyclerviewandobjects;

public class Person {

    int id;
    String name,country;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}
(c). Our MainActivity
  • Our launcher activity
  • We set our layoutmanager as well as our adapter instance to our RecyclerView.
  • We fill our arraylist with data.
package com.tutorials.hp.recyclerviewandobjects;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.tutorials.hp.recyclerviewandobjects.m_Recycler.MyAdapter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Person> people=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //RECYCLERVIEW
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //FILL LIST
        fillPeople();

        //ADAPTER
        MyAdapter adapter=new MyAdapter(this,people);
        rv.setAdapter(adapter);

    }

    private void fillPeople()
    {
        people.clear();

        Person p=new Person();
        p.setName("Micky");
        p.setCountry("Armenia");
        people.add(p);

        p=new Person();
        p.setName("Nemanja");
        p.setCountry("Serbia");
        people.add(p);

        p=new Person();
        p.setName("Lucy");
        p.setCountry("Russia");
        people.add(p);

        p=new Person();
        p.setName("Rebecca");
        p.setCountry("South Africa");
        people.add(p);

        p=new Person();
        p.setName("Singh");
        p.setCountry("India");
        people.add(p);

        p=new Person();
        p.setName("Kurt");
        p.setCountry("France");
        people.add(p);

        p=new Person();
        p.setName("Vicente");
        p.setCountry("Spain");
        people.add(p);
    }
}
(d). Our ViewHolder class
  • Holds our textviews for recycling.
package com.tutorials.hp.recyclerviewandobjects.m_Recycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.tutorials.hp.recyclerviewandobjects.R;

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView nameTxt,countryTxt;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
        countryTxt= (TextView) itemView.findViewById(R.id.countryTxt);

    }

}
(e). Our Adapter class
  • Responsible for layout inflation.
  • Also binding data to our views
package com.tutorials.hp.recyclerviewandobjects.m_Recycler;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tutorials.hp.recyclerviewandobjects.Person;
import com.tutorials.hp.recyclerviewandobjects.R;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<Person> people;

    public MyAdapter(Context c, ArrayList<Person> people) {
        this.c = c;
        this.people = people;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(people.get(position).getName());
        holder.countryTxt.setText(people.get(position).getCountry());

    }

    @Override
    public int getItemCount() {
        return people.size();
    }
}
(f). Model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="5dp"
    android:layout_height="200dp">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name"
        android:id="@+id/nameTxt"
        android:padding="10dp"
        android:textColor="@color/colorAccent"
        android:textStyle="bold"
        android:layout_alignParentLeft="true"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Country"
        android:id="@+id/countryTxt"
        android:padding="10dp"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"
        android:layout_alignParentLeft="true"
        />
</LinearLayout>
</android.support.v7.widget.CardView>
(g). Download

GitHub : Source

4. Android RecyclerView CardView and OnItemClick

Hello android recyclerview onItemClick here, this is what we cover :

  1. LinearLayout RecyclerView with cardview view items.
  2. ViewHolder to hold our views.
  3. Adapter where we inflate our layouts and bind data to views.
  4. Handle ItemClicks for our RecyclerView,in which case we show a simple Toast message.
(a). Our MainActivity.
  • Launcher activity.
  • Setup RecyclerView with its LayoutManager and adapter
  • Get data
package com.tutorials.hp.simplerecyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.tutorials.hp.simplerecyclerview.m_Recycler.MyAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //SET UP RECYCLERVIEW
        RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        //ADAPTER
        MyAdapter adapter=new MyAdapter(this,getData());
        rv.setAdapter(adapter);

    }

    //FILL DATA
    private ArrayList<String> getData()
    {
        ArrayList<String> languages=new ArrayList<>();
        languages.clear();

        //FILL
        languages.add("Java");
        languages.add("C#");
        languages.add("VB.NET");
        languages.add("PHP");
        languages.add("Python");
        languages.add("Ruby");
        languages.add("C");
        languages.add("C++");
        languages.add("Fortran");
        languages.add("Cobol");
        languages.add("Perl");
        languages.add("Prolog");

        return languages;
    }
}
(b). Our ViewHolder class.
  • Holds our views for recycling
  • Listen for View onClick events.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.tutorials.hp.simplerecyclerview.R;

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView nameTxt;
    ItemClickListener itemClickListener;

    public MyViewHolder(View itemView) {
        super(itemView);

        nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);

        itemView.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener itemClickListener)
    {
        this.itemClickListener=itemClickListener;
    }

    @Override
    public void onClick(View view) {
        this.itemClickListener.onItemClick(this.getLayoutPosition());
    }
}
(c). Our Adapter class.
  • We inflate our layout
  • Then bind data to views.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

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.Toast;

import com.tutorials.hp.simplerecyclerview.R;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    Context c;
    ArrayList<String> languages;

    public MyAdapter(Context c, ArrayList<String> languages) {
        this.c = c;
        this.languages = languages;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        //BIND DATA
        holder.nameTxt.setText(languages.get(position));

        //ITEM CLICK
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                Toast.makeText(c, languages.get(pos), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return languages.size();
    }
}
(d). Our ItemClickListener Interface.
package com.tutorials.hp.simplerecyclerview.m_Recycler;

public interface ItemClickListener {

    void onItemClick(int pos);

}
(e). Model.xml
  • Our model layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="5dp"
    android:layout_height="200dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Name"
                android:id="@+id/nameTxt"
                android:padding="10dp"
                android:textColor="@color/colorAccent"
                android:textStyle="bold"
                android:layout_alignParentLeft="true"
                />
</android.support.v7.widget.CardView>
Download

Download code below:

GitHub : Source

20+ RecyclerView Examples

Let's look at some examples.

Android RecyclerView Examples.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post