Android Tutorial: RecyclerView

Android RecyclerView is the more advanced version of ListView or GridView with improved performance and other benefits. Using RecyclerView and CardView together, both lists and grids can be created very easily. Here is the complete information about RecyclerView and other examples.

Advantages of Android RecyclerView

1. ViewHolder Pattern

In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In the case of RecyclerView, this is mandatory to use the RecyclerView.ViewHolder class. This is one of the major differences between ListView and RecyclerView.

It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.

2. LayoutManager

This is another massive enhancement brought to RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.

Now using a RecyclerView, we can have a

i) LinearLayoutManager— which supports both vertical and horizontal lists,

ii) StaggeredLayoutManager— which supports Pinterest like staggered lists,

iii) GridLayoutManager— which supports displaying grids as seen in Gallery apps.

And the best thing is that we can do all these dynamically as we want.

3. Item Animator

ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.

4. Item Decoration

In the case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in the case of RecyclerView, the RecyclerView.ItemDecoratorclass gives huge control to the developers but makes things a bit more time-consuming and complex.

5. RecyclerView.Adapter

RecyclerView includes a new kind of adapter. It’s a similar approach to the ones you already used, but with some peculiarities, such as a required ViewHolder. You will have to override two main methods: one to inflate the view and its view holder, and another one to bind data to the view. The good thing about this is that the first method is called only when we really need to create a new view. No need to check if it’s being recycled.

Recyclerview Android Dependency

For using RecyclerView in your project you need to add the recycler view support library to your project. Add the following Gradle dependency to the project build.gradle file.

dependencies {
    implementation "androidx.recyclerview:recyclerview:1.1.0"
}

Create a layout with RecyclerView

Add android Recyclerview into activity_main.xml

<?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="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"/>
</RelativeLayout>

Create Data Model

Create a Model class to hold the data for the recyclerview. In my case, I am using Items.java model class.

public class Items {

    private String name;
    private int price;

    Items(String mName,int mPrice){
        this.name = mName;
        this.price = mPrice;
    }

    public int getPrice() {
        return price;
    }

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

    public String getName() {
        return name;
    }

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

Prepare Adapter for the Recyclerview

Recylerview adapter is used to hold the view with data. For that, we need to design the layout resource file item_row.xml first.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/itemLayout"
    android:focusable="true"
    android:clickable="true"
    android:background="#C3C3C3"
    android:layout_margin="10dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/tvName"
        tools:text="@tools:sample/full_names"
        android:padding="5dp"
        android:textStyle="bold"
        android:textColor="#121212"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        tools:text="@tools:sample/full_names"
        android:padding="5dp"
        android:textColor="#121212"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/tvPrice" />
</LinearLayout>

The design will be look like this,

The UI for the recyclerview adapter is ready. next, create the adapter for the recyclerview. RecyclerView adapter should extend the RecyclerView.Adapter<ViewHolder>.

Also, We Recyclerview needed ViewHolder to hold the view items.

RecyclerviewItemAdapter.java

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

    private List<Items> itemsList;
    private ClickListener clickListener;

    RecyclerviewItemAdapter(List<Items> mItemList){
        this.itemsList = mItemList;
    }

    @Override
    public RecyclerviewItemAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerviewItemAdapter.MyViewHolder holder, final int position) {
        final Items item = itemsList.get(position);
        holder.name.setText(item.getName());
        holder.price.setText(String.valueOf(item.getPrice()));
        
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder{

        public TextView name,price;
        private LinearLayout itemLayout;

        public MyViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tvName);
            price = itemView.findViewById(R.id.tvPrice);
            itemLayout =  itemView.findViewById(R.id.itemLayout);
        }
    }
}

Prepare data for recyclerview

Once the adapter is created, we need to prepare data for the recyclerview. So that, we can set it into recyclervirew using an adapter. in MainActivity.java

private void prepareItems(){
        for(int i = 0; i < 50; i++) {
            Items items = new Items("Item"+i,20+i);
            itemsList.add(items);
        }
}


In most cases, We use REST API to fetch data from the server. Check the below link for retrofit android with recyclerview.

Set Recyclerview Adapter to Recyclerview

In previous, we created adapter and data for the recyclerview. Now, we need to set it into recyclerview.

recyclerviewItemAdapter = new RecyclerviewItemAdapter(itemsList);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recyclerviewItemAdapter);


That’s it, we created the recyclerview with data. Now you can able run this and see the data in the recyclerview.

Implementing click listener for recyclerview

To implement click listener, First, we need to create an interface for the adapter and the recyclerview android.

create ClickListener.java and add the needed interface.

public interface ClickListener<T> {
    void onClick(View view, T data, int position);
}

In my case, I am having one interface for the recyclerview item click listener.

Next, in your RecyclerviewViewAdapter create a method to get the clickListener instance from your MainActivity.

public void setOnItemClickListener(ClickListener clickListener) {
        this.clickListener = clickListener; 
}


in MainActivity.java, Call this method with the ClickListener implementation.

recyclerviewItemAdapter.setOnItemClickListener(new ClickListener<Items>(){
            @Override
            public void onClick(View view, Items data, int position) {
                Toast.makeText(getApplicationContext(),"Position = "+position+"\n Item = "+data.getName(),Toast.LENGTH_SHORT).show();

            }
});

Done. we can able to click and get the callback for the recyclerview clicks. Download the source code for the example in github.

Comments

Android Tutorial: Layouts - Digital Juices

[…] Layouts are important because they directly affect the look and feel of your application. Technically, a layout is a view that arranges child views added to it. Android comes with a number of built-in layouts, ranging from LinearLayout, which is the easiest to use, to RelativeLayout, which is the most powerful. This article discusses the various layouts in Android. Related article: Android Tutorial: RecyclerView […]

Leave a Reply

Your email address will not be published.