Using RecyclerView in Android

By | January 26, 2019

In your Android application, whenever you want to display a list of data, you can use RecyclerView. Earlier Android provide ListView which was used for the same thing. RecyclerView can be thought of as a more advanced and performance optimized version of ListView. As the name suggests, RecyclerView also recycles the items by using the ViewHolder pattern. Along with that, it also Uses a LayoutManager which gives more flexibility of creating horizontal, vertical or even Staggered lists. It also offers vertical and horizontal scrolling along with item animations. While the ListView can also be modified to use the ‘ViewHolder’ pattern, RecyclerView enforces the use of the same. It can even deal with large quantity of data while providing a responsive interface.

In this post, we will see how to implement a simple RecyclerView in Android application using Android Studio. I will be using Android studio version for the same

Create a New Project

  1. Open Android Studio. Go to File -> “New Project”, fill in the application name and other details, select the API version as API 15. Select Empty activity, keep the default options in next screen and click finish. The new project will be created along with required files. (In the example I have given the Application Name as “SimpleRecyclerViewExample” and package as “com.example”
  2. To use RecyclerView, we need to add recycler view dependency. Open build.gradle(Module:app) file and add the following “implementation ‘com.android.support:recyclerview-v7:26.1.0’” in the dependencies section. Click sync now to sync the changes and build the project.
  3. Open activity_main.xml in the layout folder and add the Recycler View widget. The xml file should look like below after the change
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.simplerecyclerviewexample.MainActivity">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rvFootballTeamInfo"
    android:scrollbars="vertical"
    ></android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

For the Recycler view, we have provided an id and specified the scrollbars to be vertical

Create Model Class and Layout File

  1. We will display Football Team related information in the Recycler view. We will create a model class for storing the info. Create a class FootballTeam.java and create variable for Name, League and YearEstablished
package com.example.simplerecyclerviewexample;


public class FootballTeam {

    private String name;
    private String league;
    private int yearEstablished;

    public FootballTeam() {

    }

    public FootballTeam(String name, String league, int yearEstablished) {
        this.name = name;
        this.league = league;
        this.yearEstablished = yearEstablished;
    }

    public String getName() {
        return name;
    }

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

    public String getLeague() {
        return league;
    }

    public void setLeague(String league) {
        this.league = league;
    }

    public int getYearEstablished() {
        return yearEstablished;
    }

    public void setYearEstablished(int yearEstablished) {
        this.yearEstablished = yearEstablished;
    }
}
  1. Create a layout file called row.xml. This layout will be used for displaying each record in the recycler view. We will create a simple RelativeLayout containing three text views for displaying the name, league and year established. The full xml for the layout is shown below
<?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="wrap_content"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp" >
    
    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        tools:text="Team Name"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvLeague"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="Team League"
        android:layout_below="@id/tvName" />

    <TextView
        android:id="@+id/tvYear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="1999"
        android:layout_alignParentRight="true"
         />

</RelativeLayout>

For this example, I have directly hardcoded the padding and textSize in the xml but it is always a good idea to have the same in a separate xml file. I have used the “tools:Text” attribute to find out how my layout will look in the designer. The same is not going to be rendered when the application is run.

Creating the Adapter

Now that we have created the Model and the item layout, it is time to create our adapter class. The adapter class is responsible for creating the ViewHolder objects as well as binding the data to them

  1. Create a class called MyAdapter.java and put the below code
package com.example.simplerecyclerviewexample;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    public List<FootballTeam> teamList;

    public MyAdapter(List<FootballTeam> footballTeamList) {
        teamList = footballTeamList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView name, league, yearEstablished;

        public ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
            league = (TextView) itemView.findViewById(R.id.tvLeague);
            yearEstablished = (TextView) itemView.findViewById(R.id.tvYear);

        }
    }

    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.name.setText(teamList.get(position).getName());
        holder.league.setText(teamList.get(position).getLeague());
        holder.yearEstablished.setText(String.valueOf(teamList.get(position).getYearEstablished()));

    }

    @Override
    public int getItemCount() {
        return teamList.size();
    }
}

Our Adapter class extends the RecyclerView.Adapter class and manages all the ViewHolder objects. We have defined our ViewHolder class inside our adapter and we have initialized the TextViews inside the ViewHolder constructor.

The adapter is responsible for creating the ViewHolder objects as needed. It also created new viewHolder objexts as the user scrolls through the list items. There are three important methods that we need to override.

The “onCreateViewHolder()” method is used for creating the ViewHolder and we are inflating the layout that we created earlier inside it.

The “onBindViewHolder()” method is used to bind the data to the ViewHolder. It determines the data that needs to be displayed based on the list position and populated the ViewHolder.

The “getItemCount()” method returns the size of the dataset. In our case that will be the number of items in the teamList.

We have also created a constructor using which we will assign the teamList collection which we will pass through our Mainactivity. Now that we have created our adapter, it is time to bind everything together.

Main Activity Changes

  1. Open MainActivity.java and make the changes shown below
package com.example.simplerecyclerviewexample;

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

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView rvTeams;
    List<FootballTeam> teamList = new ArrayList<>();
    MyAdapter adapter;

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

        rvTeams = (RecyclerView) findViewById(R.id.rvFootballTeamInfo);

        setTeamData();

        adapter = new MyAdapter(teamList);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(getApplicationContext());
        rvTeams.setLayoutManager(manager);
        rvTeams.setAdapter(adapter);


    }

    private void setTeamData() {
        FootballTeam team = new FootballTeam("Manchester United", "English Premier League", 1878);
        teamList.add(team);

        team = new FootballTeam("Arsenal", "English Premier League", 1886);
        teamList.add(team);

        team = new FootballTeam("Liverpool", "English Premier League", 1892);
        teamList.add(team);

        team = new FootballTeam("Juventus", "Serie A", 1897);
        teamList.add(team);

        team = new FootballTeam("Real Madrid", "La Liga", 1902);
        teamList.add(team);

        team = new FootballTeam("Bayern Munich", "Bundesliga", 1900);
        teamList.add(team);

        team = new FootballTeam("PSG", "France Ligue 1", 1970);
        teamList.add(team);

        team = new FootballTeam("Ajax", "Eredivisie", 1900);
        teamList.add(team);
    }
}

In The MainActivity.java file, we have created a reference to our recycler view and we have also created variables for our Adapter and list. We have used the setTeamData() method to populate our ArrayList with the data that we are going to display in the RecyclerView.

In the “onCreate()” method, we are creating a LinearLayoutManager and assigning the same to our RecyclerView. The LayoutManager is used by recycler view to position each individual item on screen. We have used LinearLayoutManager to position the items horizontally. Other type of options includes GridLayoutManager and StaggeredGridLayoutManager. We can also create our custom layout manager if we want.

After setting the layout manager, we are assigning our custom adapter to the recycler view. On running the application, you will see the list of items displayed in the List as shown in the image below. You will also be able to scroll the list. RecyclerView also provides different options to specify the animation, or you can implement an onclick listener if you want the items in the list to be clickable and you want to perform some action on the list item click.

Download Code