Android RecyclerView Tutorial

Android RecyclerView widget

RecyclerView Implementation

Hey Technoz, This RecyclerView implementation tutorial comes with the solution to the dynamic listing of elements. The android RecyclerView is an advanced version of ListView in android. When we want to display some large list of items, then RecyclerView is a best option. It creates and binds some view holders on either side of the list. As soon as the user scrolls the list, the RecyclerView creates new view holders as necessary. It also saves the view holders which have scrolled off-screen, so they can be reused. The RecyclerView widget reuses old view holders with the new updated data. Thus, it reduces the memory consumption and improves the app’s performance. Of course, you can read more about RecyclerView widget on the Android Develper’s Site.

In our android recyclerview implementation project, we are showing a list of products with their price and description. So, lets start.

Add the gradle dependency

At first, to add RecyclerView widget, we need to add its gradle dependency in app-level build.gradle as follows. It is mandatory step in RecyclerView implementation.

dependencies {
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

Create the activity with RecyclerView

Now create a new empty activity. We will place our RecyclerView widget in this activity. Lets design the xml file first. In my case, it is activity_products.xml

<?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=".ProductsActivity">

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

</android.support.constraint.ConstraintLayout>

Lets see the java file as below. It is ProductsActivity.java.

package net.softglobe.tutorials;

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

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

public class ProductsActivity extends AppCompatActivity {

    private List<Product> productList = new ArrayList<>();
    private RecyclerView recyclerView;
    private ProductsAdapter pAdapter;
    RecyclerView.LayoutManager pLayoutManager;
    public static final String URL_ALL_PROD = "http://192.168.43.17/newprojectapp/get_all_product_details.php";

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

        recyclerView = findViewById(R.id.recycler_view);

        // use a linear layout manager
        pLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(pLayoutManager);

        // specify an adapter
        pAdapter = new ProductsAdapter(productList);
        recyclerView.setAdapter(pAdapter);

        recyclerView.setItemAnimator(new DefaultItemAnimator());

        prepareProductData();
    }

public void prepareProductData(){
        Product product = new Product("Cello Pinpoint", "10 INR", "Cello Pinpoint Pen 0.6");
        productList.add(product);

        product = new Product("HP Laptop", "45000 INR", "Hp Pavilion Notebook");
        productList.add(product);

        product = new Product("Sony Bravia", "100000 INR", "Sony Bravia LED Plasma TV");
        productList.add(product);

        product = new Product("Dell Inspiron", "42500 INR", "Dell Corporation Laptop");
        productList.add(product);

        product = new Product("Stamp Pad", "30 INR", "Camel Stamp Pad");
        productList.add(product);
    }
}

In above file, we have created an array of products list and added some items in it. We have here defined Adapter to bind data and LinearLayoutManager to fill the views.

Create class for getting and setting values

To get and set values of TextViews in our views, we are creating a new class Product.java with getter and setter methods.

package net.softglobe.tutorials;

public class Product {
    private String name, price, description;

    public Product(){
    }

    public Product(String name, String price, String description){
        this.name = name;
        this.price = price;
        this.description = description;
    }

    public String getName(){
        return name;
    }

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

    public String getPrice(){
        return price;
    }

    public void setPrice(String price){
        this.price = price;
    }

    public String getDescription(){
        return description;
    }

    public void setDescription(String description){
        this.description = description;

    }
}

So, we are here assigning the values to the strings as name, price and description which are sent to this class. Also, we can get back these values when required using getter methods.

Design the repeating view

The RecyclerView duplicates the same view dynamically with different values in it. So, we have to create the layout of single view which gets repeatedly generated as required. For recyclerview implementation, create the file product_list_row.xml as follows.

<?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:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical"
    android:paddingBottom="@dimen/row_padding_vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/row_padding_vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:textColor="@color/title"
        android:textSize="16dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:textColor="@color/year"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

Add an Adapter

In order to feed the data to the list, we create and Adapter class. We extend this class to RecyclerView.Adapter class. This object creates views for items, and replaces the content of some of the views with new data items when the original item is no longer visible. Create the following java file ProductsAdapter.java

package net.softglobe.tutorials;

import android.support.annotation.NonNull;
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.List;

public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.MyViewHolder> {

    private List<Product> productsList;

    public class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView name, price, description;

        public MyViewHolder(View view){
            super(view);
            name = (TextView) view.findViewById(R.id.name);
            price = (TextView) view.findViewById(R.id.price);
            description = (TextView) view.findViewById(R.id.description);
        }
    }

    ProductsAdapter(List<Product> productsList){
        this.productsList = productsList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_list_row,parent,false);

        return new MyViewHolder(itemView);
    }


    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Product product = productsList.get(position);
        holder.name.setText(product.getName());
        holder.price.setText(product.getPrice());
        holder.description.setText(product.getDescription());
    }

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

We have created a class MyViewHolder which contains all the views we require to fill the values in. The method OnCreateViewHolder() inflates the layout file product_list_row.xml. Similarly, the next method onBindViewHolder() gets the values from Products.java and it set the values according to the position of item.

Finally, we are done with the project. Now lets try running what we have made. You will see the RecyclerView implementation, listing 5 items in the array. Please see the screenshot below.

Android RecyclerView Tutorial

Please note that the products listed above does not necessarily belongs to the actual prices, descriptions and other data. It is only for demonstration purpose. The name of brands are the property of their respective owners.

Download Source Code

Especially, if you want to jump directly to the RecyclerView implementation, the source code is always available to download from below link.

If you have any doubts or problems in implementing this tutorial, please comment below. Please subscribe to our newsletter to catch such knowledgeable and understanding tutorials.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.