Android RecyclerView tutorial for beginners


Android RecyclerView is a more advanced version of a list view with improved performance and other major benefits. When combined with CardView, it can render even a more complex list. Here is a complete and advanced tutorial on how to use both RecyclerView and CardView in android.

Under this tutorial, we are going to learn how to render a simple android RecyclerView using a custom layout, adapters and model class.

1. Creating android RecyclerView User Interface

Following is the UI of RecyclerView widget with necessary attributes

Also Read: How to hide android Floating Action Button as one scrolls Recycler View

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


Create new Android Project

In Android Studio go to FILE => New Project and fill in all the necessary details needed for the project. When promted to select default activity, select Basic Activity and proceed.

Also Read: Endless Scrolling RecyclerView

For those using android studio version 2.0 and above, it will create two layouts by default for the Main Activity; activity_main.xml (Contains CoordinatorLayout and AppBarLayout) and content_main.xml(for the actual content). Inside content_main.xml, add Add RecyclerView widget as shown below. Also remeber to change the root layout of content_main.xml from Constrain Layout to RelativeLayout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="hacksmileandroid.com.androidrecyclerviewtutorial.MainActivity"
    tools:showIn="@layout/activity_main">

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


</RelativeLayout>

After creating the RecyclerView widget, the next thing would be to create a custom layout that will represent a single row in a RecyclerView. To create a new custom layout, right click on layout => New Layout File, then fill in the name of your layout file and click finish.



<?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="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Our Recycler Title"
        android:textColor="#000"
        android:textSize="21sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/text_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="Small description here"
        android:textColor="#000" />

</LinearLayout>

Creating RecyclerView Adapter

After creating a single row of RecyclerView, let’s start by writing an adapter class that will hold RecyclerView data.

Read Also: How to create android setting screen using PreferenceFragement

Create a class named ModelClass.java which is part of our adapter. This class will declare every single item contained in ReycclerView:

package hacksmileandroid.com.androidrecyclerviewtutorial;


public class ModelClass {
    // our recycler view has two items, i.e title, and description
    // so include them here

    private String title;
    private String description;

    public ModelClass(String title, String description) {
        this.title = title;
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }
}

Now create a class named RecyclerAdapter.java. This is the class where we will inflate our custom layout. Full details and explanation of this class can be found after it’s code.

package hacksmileandroid.com.androidrecyclerviewtutorial;

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 java.util.ArrayList;

/**
 * Created by Benson on 28-May-18.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyCustomViewHolder> {

    private Context context;
    private ArrayList<ModelClass> modelClasses;


    public RecyclerAdapter(Context context, ArrayList<ModelClass> modelClasses) {
        this.context = context;
        this.modelClasses = modelClasses;
    }

    @Override
    public RecyclerAdapter.MyCustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyCustomViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.MyCustomViewHolder holder, int position) {
        holder.titleText.setText(modelClasses.get(position).getTitle());
        holder.descriptionText.setText(modelClasses.get(position).getDescription());
    }

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


    public class MyCustomViewHolder extends RecyclerView.ViewHolder {

        private TextView titleText;
        private TextView descriptionText;

        public MyCustomViewHolder(View view) {
            super(view);

            titleText = (TextView) view.findViewById(R.id.text_title);
            descriptionText = (TextView) view.findViewById(R.id.text_description);

        }
    }

}

Don’t worry if you found this code misleading, most of the code contained above is generated by the android studio, in short, it’s nothing but method implementation. This class should always contain 3 methods; onCreateViewHolder(which returns view). The view is the custom layout that we created, the custom layout that we said, represents a single row in Recyclerview. The second method that must be implemented in this class is onBindViewHolder(Keeps recycling or rebuilding View Holder the custom layout), the third method to be implemented is getItemCount(returns the number of items or rows in our Recyclerview). Number of elements to be returned is gotten from the data structure. There must also be a custom class that inherits from RecyclerView.ViewHolder.



Finally, it’s time to create our RecyclerView in the MainActivity.java.

package hacksmileandroid.com.androidrecyclerviewtutorial;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        ArrayList<ModelClass> modelClasses = new ArrayList<>();
        RecyclerAdapter recyclerAdapter = new RecyclerAdapter(this, modelClasses);

        recyclerView.setAdapter(recyclerAdapter);

        // now let's set content for our Recycler View

        String[] titles = {
                "First Title",
                "Second Title",
                "Third Title",
                "Fourth Title"
        };

        String[] descriptions = {
                "This is description for the first section. It must come here",
                "This is description for the second section. It must come here",
                "This is description for the third section. It must come here",
                "This is description for the fourth section. It must come here"
        };


        for (int i = 0; i < titles.length &amp;&amp; i < descriptions.length; i++) {
            modelClasses.add(new ModelClass(
                    titles[i],
                    descriptions[i]
            ));

            recyclerAdapter.notifyItemInserted(modelClasses.size() - 1);

        }


    }
}