Recyclerview Android Example [Beginners]

Recyclerview Android in the advanced version of the listview. Recyclerview simplifies the display and handle of the large set of data. It’s coming with default animations. Recyclerview provides layout managers for positioning items.

Recyclerview Official documentsays,

If your app needs to display a scrolling list of elements based on large data sets (or data that frequently changes), you should use RecyclerView as described on this page.

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 the 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 doall 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 case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in 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

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.

Also, I have added another post on adding pagination for the recyclerview.

https://medium.com/android-beginners/pagination-with-recyclerview-in-android-3e099c65b6a3

Done with the explanation. Let’s create a sample application with recyclerview android.

1. 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"
}

2. Create 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>

3. 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;
    }

}

4. Prepare Adapter for the Recyclerview

Recylerview adapter 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 looks 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);
        }
    }
}

5. Prepare data for recyclerview

Once the adapter 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 below link for retrofit android with recyclerview.

6. 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);

Thats it. we created the recyclerview with data. Now you can able run this and see the data in the recyclerview.

7. Implementing click listener for recyclerview

To implement click listener, First we need to create 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 once interface for the recyclerview item click listener.

Next, in your RecyclerviewViewAdapter create 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 you can able to click and get the callback for the recyclerview clicks.

Download the source code for the example in github.

Checkout my other post on recyclerview.

Android Recyclerview Search Filter Example

Android Recyclerview Swipe Menu Example

Expandable Recyclerview Android Example [Updated]

Conclusion

Thanks for the reading. In recent time, we are using recyclerview every day. So try to do the sample with the recyclerview and let me know your doubts in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *