RecyclerView is the most advanced, powerful, and flexible version of ListView. In this tutorial, we are going to learn, how to display data in RecyclerView? We will learn RecyclerView Adapter, Encapsulation, CardView, ItemDecoration, View Holder and Layout Manager. By using RecyclerView, we can display data in three ways.

1- Vertical View

2- Horizontal View

3- GridView

Step-1:

Let’s create a new project. Open Android Studio and create a new project. Enter the required information for creating the project and select blank Activity and proceed. When your project will create then make sure you have added the following dependencies in your project.

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

Step-2:

Now let’s display data in VerticalView. First, you need to create a design for VerticalView. I created a new layout file named adapter_vertical.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp">

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#097A05"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/txtPopulation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtTitle"
        android:layout_alignParentEnd="true"
        android:textColor="#027C71"
        android:textSize="14sp" />

</RelativeLayout>

Step-3:

Now I will create the model class which will contain two properties title and population of the country.

package com.becody.example.recyclerview.modals;

/**
 * Created by becody.com on 19,07,2020
 */
public class CountryM {
    private String title;
    private String population;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPopulation() {
        return population;
    }

    public void setPopulation(String population) {
        this.population = population;
    }
}

Step-4:

Now you can see, I designed a layout for VerticalView. Now I will create VerticalAdapter using ViewHolder. You can see the code of VerticalAdapter.java class.

package com.becody.example.recyclerview.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.becody.example.recyclerview.R;
import com.becody.example.recyclerview.modals.CountryM;

import java.util.List;

/**
 * Created by becody.com on 19,07,2020
 */
public class AdapterVertical extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<CountryM> dataList;

    public AdapterVertical(List<CountryM> dataList) {
        this.dataList = dataList;
    }

    private class CellViewHolder extends RecyclerView.ViewHolder {
        private TextView txtTitle;
        private TextView txtPopulation;

        public CellViewHolder(View itemView) {
            super(itemView);
            txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            txtPopulation = (TextView) itemView.findViewById(R.id.txtPopulation);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            default: {
                View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_vertical, parent, false);
                return new CellViewHolder(v1);
            }
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            default: {
                CellViewHolder cellViewHolder = (CellViewHolder) holder;
                CountryM data = dataList.get(position);
                cellViewHolder.txtTitle.setText(data.getTitle());
                cellViewHolder.txtPopulation.setText(data.getPopulation());
                break;
            }
        }
    }

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

Step-5:

Now we will design Main Activity design. Let’s create a design for the MainActivity.java class.

<?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:layout_margin="10dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3">

        <Button
            android:id="@+id/btnVertical"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#052CEF"
            android:text="@string/title_vertical"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/btnHorizontal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:layout_weight="1"
            android:background="#2196F3"
            android:text="@string/title_horizontal"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/btnGridView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"

            android:layout_weight="1"
            android:background="#FF9800"
            android:text="@string/title_grid_view"
            android:textColor="#FFFFFF" />


    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />

</LinearLayout>

Step-6:

Now we will populate the data for List. I have added array of sample in strings.xml file.

<resources>
    <string name="app_name">RecyclerView Example</string>
    <string-array name="country_list">
        <item>Afghanistan - 38,928,346</item>
        <item>Albania - 2,877,797</item>
        <item>Algeria - 43,851,044</item>
        <item>Andorra - 77,265</item>
        <item>Angola - 32,866,272</item>
        <item>Antigua and Barbuda - 97,929</item>
        <item>Argentina - 45,195,774</item>
        <item>Armenia - 2,963,243</item>
        <item>Australia - 25,499,884</item>
        <item>Austria - 9,006,398</item>
        <item>Azerbaijan - 10,139,177</item>
        <item>Bahamas - 393,244</item>
        <item>Bahrain - 1,701,575	</item>
        <item>Bangladesh - 164,689,383</item>
    </string-array>
    <string name="title_vertical">Vertical \n View</string>
    <string name="title_horizontal">Horizontal \n View</string>
    <string name="title_grid_view">Grid \n View</string>
</resources>

Now we will populate the data for list.

    private void populateData() {
        String[] countryArr = getResources().getStringArray(R.array.country_list);
        for (String str : countryArr) {
            String[] splitVal = str.split("-");
            CountryM countryM = new CountryM();
            countryM.setTitle(splitVal[0]);
            countryM.setPopulation(splitVal[1]);
            countryMList.add(countryM);
        }
    }

Step-7:

Now create the object of LinearLayoutManager and set the orientation Vertical like this

  private void showRecyclerViewInVerticalDirection() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        listing.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(listing.getContext(),
                linearLayoutManager.getOrientation());
        listing.addItemDecoration(dividerItemDecoration);
        AdapterVertical adapterVertical = new AdapterVertical(countryMList);
        listing.setAdapter(adapterVertical);
    }

When you will execute the code on this stage, you will have display like this

Vertical RecyclerView
Vertical RecyclerView

Step-8:

Now I will create the design for horizontal RecyclerView. This is possible that we will have a different design for Vertical and Horizontal View. So let’s create a design first.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="150dp"
    android:layout_height="100dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="5dp"
    android:elevation="5dp"
    app:cardBackgroundColor="#532F95"
    android:layout_margin="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFF"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/txtPopulation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:textColor="#FFFFFF"
            android:textSize="14sp" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>

Step-9:

Same like Vertical Adapter, we will create a new adapter class named HorizontalAdapter.java.

package com.becody.example.recyclerview.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.becody.example.recyclerview.R;
import com.becody.example.recyclerview.modals.CountryM;

import java.util.List;

/**
 * Created by becody.com on 19,07,2020
 */
public class AdapterHorizontal extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<CountryM> dataList;

    public AdapterHorizontal(List<CountryM> dataList) {
        this.dataList = dataList;
    }

    private class CellViewHolder extends RecyclerView.ViewHolder {
        private TextView txtTitle;
        private TextView txtPopulation;

        public CellViewHolder(View itemView) {
            super(itemView);
            txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            txtPopulation = (TextView) itemView.findViewById(R.id.txtPopulation);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            default: {
                View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_horizontal, parent, false);
                return new CellViewHolder(v1);
            }
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            default: {
                CellViewHolder cellViewHolder = (CellViewHolder) holder;
                CountryM data = dataList.get(position);
                cellViewHolder.txtTitle.setText(data.getTitle());
                cellViewHolder.txtPopulation.setText(data.getPopulation());
                break;
            }
        }
    }

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

Step-10:

Now we will create the object of LinearLayoutManager class and will set the orientation Horizontal. Now you will how much is easy to display data in both Vertical and Horizontal orientation using RecyclerView.

private void showRecyclerViewInHorizontalDirection() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        listing.setLayoutManager(linearLayoutManager);
        AdapterHorizontal adapterVertical = new AdapterHorizontal(countryMList);
        listing.setAdapter(adapterVertical);
    }

Now display should like this

Horizontal RecyclerView.
Horizontal RecyclerView

I hope, you have learned both ways of LinearLayoutManager. If you have still any confusion about LinearLayoutManager or RecyclerView, you can ask by the comment, or you can ask in Becody WhatsApp group.

Step-11:

If you learned LinearLayoutManager. Then GridLayoutManager is so easy to display data. I will reuse the HorizontalAdapter.java class for this example. Let’s create the object of the GrildLayoutManager class. In GrildLayoutManager class, you can set columns with your requirement of design.

 private void showRecyclerViewInGridView() {
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this,2);
        listing.setLayoutManager(linearLayoutManager);
        AdapterHorizontal adapterVertical = new AdapterHorizontal(countryMList);
        listing.setAdapter(adapterVertical);
    }

After execute the code, the display should like this

GridLayoutManager
GridView

Here is the full code of the RecyclerViewActivity.java file. I have added three buttons for Vertical, Horizontal, and GridView. You can change any views by click on these buttons.

package com.becody.example.recyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;

import com.becody.example.recyclerview.adapters.AdapterHorizontal;
import com.becody.example.recyclerview.adapters.AdapterVertical;
import com.becody.example.recyclerview.modals.CountryM;

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

public class RecyclerViewActivity extends AppCompatActivity {
    private RecyclerView listing;
    private List<CountryM> countryMList;
    private Button btnVertical, btnHorizontal, btnGrid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        countryMList = new ArrayList<>();
        listing = findViewById(R.id.listing);
        btnGrid = findViewById(R.id.btnGridView);
        btnHorizontal = findViewById(R.id.btnHorizontal);
        btnVertical = findViewById(R.id.btnVertical);

        btnHorizontal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRecyclerViewInHorizontalDirection();
            }
        });
        btnGrid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRecyclerViewInGridView();
            }
        });

        btnVertical.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRecyclerViewInVerticalDirection();
            }
        });
        populateData();
        showRecyclerViewInVerticalDirection();
    }

    private void populateData() {
        String[] countryArr = getResources().getStringArray(R.array.country_list);
        for (String str : countryArr) {
            String[] splitVal = str.split("-");
            CountryM countryM = new CountryM();
            countryM.setTitle(splitVal[0]);
            countryM.setPopulation(splitVal[1]);
            countryMList.add(countryM);
        }
    }

    private void showRecyclerViewInVerticalDirection() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        listing.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(listing.getContext(),
                linearLayoutManager.getOrientation());
        listing.addItemDecoration(dividerItemDecoration);
        AdapterVertical adapterVertical = new AdapterVertical(countryMList);
        listing.setAdapter(adapterVertical);
    }

    private void showRecyclerViewInHorizontalDirection() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        listing.setLayoutManager(linearLayoutManager);
        AdapterHorizontal adapterVertical = new AdapterHorizontal(countryMList);
        listing.setAdapter(adapterVertical);
    }

    private void showRecyclerViewInGridView() {
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this,2);
        listing.setLayoutManager(linearLayoutManager);
        AdapterHorizontal adapterVertical = new AdapterHorizontal(countryMList);
        listing.setAdapter(adapterVertical);
    }
}

Thanks for reading the tutorial. Please like our Facebook page for a new and latest tutorial. Join our WhatsApp group for asking any questions about this tutorial. Please subscribe to our Youtube channel for the latest updates and tutorials.

Write A Comment