Swipe To Refresh RecyclerView Android Example | Pull To Refresh

listview section header kotlin, kotlin pick video from gallery or capture from camera, kotlin custom spinner with image, pull to refresh listview android, swipe to refresh recyclerview android, expandablelistview in kotlin, Kotlin Horizontal Progressbar Android, kotlin image slider from url, Kotlin GIF Animated Splash Screen, Kotlin RecyclerView Sectioned Header, kotlin indeterminate circular progressbar, android dexter kotlin, kotlin digital signature view, kotlin alertdialog with edittext, elasticsearch windows, android dexter kotlin

Welcome to Swipe To Refresh RecyclerView Android Example.

This Pull/swipe To Refresh RecyclerView Android Example will answer your question like “how to refresh recyclerview in android”

Swipe or pull to refresh recyclerview feature provides easy way to handle data which are updating frequently.

In this example, we will use three different lists to implement refresh facility.

One list is of cars, second is of player names and third one is of country names. I have created video for more reference.

First of all, go through the below video to show the final outcome.

 

Step 1.  Adding Gradle File Lines

Create a new project in the android studio.

For using RecyclerView and CardView, you need to add two lines into your build.gradle(Module:app) file.

Below are those two lines,

 implementation 'com.android.support:recyclerview-v7:28.0.0'
 implementation 'com.android.support:cardview-v7:28.0.0'

First one is for RecyclerView and second one is for CardView.

These lines will add some classes to our projects which we can use directly in our Java files.

Step 2. Single Drawable File

Now go to app->res->drawable directory and create a new file called cardview.xml

You need to add the below code lines in this cardview.xml file.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />
            <gradient android:startColor="#261CB7" android:endColor="#356FD5" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp"/>
        </shape>
    </item>

    <item android:state_focused="false"
        >
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />

            <gradient android:startColor="#1C24B7" android:endColor="#7D42DA" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp" />
        </shape>
    </item>

</selector>

Above lines will create the background for cardview.

It will use the gradient effect of blue colors to make attractive background for cardview.

We will use this file inside the XML layout file which we will create in the next step.

Step 3. Specific XML layout file

Now navigate to app->res->layout directory and make a new XML file.

Give this file a name like rv_child.xml and add the below code in it

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

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="0dp"
        card_view:cardCornerRadius="4dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/tv"
                android:height="100dp"
                android:background="@drawable/cardview"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:text="Image"
                android:textColor="#fff"
                android:textStyle="bold"
                android:textSize="18sp" />
    
        </LinearLayout>

    </android.support.v7.widget.CardView>
</RelativeLayout>

We are using <CardView> tag in the above file.

All the elements which are inside the <CardView> tag will have the background like the cards.

In this, we have inserted one text view.

In the background of this text view, we are using an XML file which we have created in drawable folder. (cardview.xml)

All the child rows of the recyclerview will have the view created by this rv_child.xml file.

Step 4. Model For DataSet

Now make a new JAVA class and give it a name like Model.java

Write down the below code lines in Model.java file.

public class Model {

    private String name;

    public String getName() {
        return name;
    }

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

}

There is one string variable called “name” in the above class.

For this string variable, I have created two methods.

One is getter ( getName() ) and another is setter ( setName(String name) ) .

These methods will help us to maintain the data among all the child rows of the recycler view.

We will use this class and it’s objects in the Adapter class.

Step 5. Making Adapter

Time to create adapter class. Create a new JAVA class with the name Adapter.java

Adapter.java should contain the following coding lines.

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.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 26-Jun-17.
 */
    public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {

        private LayoutInflater inflater;
        private ArrayList<Model> imageModelArrayList;


        public Adapter(Context ctx, ArrayList<Model> imageModelArrayList){

            inflater = LayoutInflater.from(ctx);
            this.imageModelArrayList = imageModelArrayList;
        }

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

            View view = inflater.inflate(R.layout.rv_child, parent, false);
            MyViewHolder holder = new MyViewHolder(view);

            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {

            holder.time.setText(imageModelArrayList.get(position).getName());
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder{

            TextView time;
            ImageView iv;

            public MyViewHolder(View itemView) {
                super(itemView);

               time = (TextView) itemView.findViewById(R.id.tv);
            }

        }
    }

Inside the constructor of the adapter class, compiler will get the arraylist with the objects of the Model.java class.

Name of this arraylist is imageModelArrayList

Now focus on the method onCreateViewHolder().

Inside this onCreateViewHolder() method, compiler will first inflate the rv_child.xml file.

Now read the method onBindViewHolder() . Inside this onBindViewHolder() method, compiler will set the text inside the text view.

To set the text inside text view, compiler will use imageModelArrayList and the methods of Model.java class.

Step 6. Final Writings of Example

Now there should be two main files when you created a new project.

Those two main files are : activity_main.xml and MainActivity.java

Inside activity_main.xml file, you have to write the below source lines

<LinearLayout 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">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="15dp" />

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

Above main XML layout file is very simple.

We need to add only RecyclerView inside this main layout file.

But we need to implement SwipeToRefresh element as the parent of the RecyclerView.

Now go to your MainActivity.java file and write the following words in it

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ArrayList<Model> imageModelArrayList;
    private Adapter adapter;
    private int currentList = 0;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    private String[] firstList = new String[]{"Benz", "Bike",
            "Car","Carrera"
            ,"Ferrari","Harly",
            "Lamborghini","Silver"};
    private String[] secondList = new String[]{"Roger", "Rafael",
            "Novak","Maria"
            ,"Serena","Andy",
            "Agasi","Tsitsipas"};
    private String[] thirddList = new String[]{"India", "USA",
            "Canada","Australia"
            ,"Singapore","Japan",
            "UK","France"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);

        imageModelArrayList = populateList(currentList);
        Log.d("hjhjh", imageModelArrayList.size() + "");
        adapter = new Adapter(this,imageModelArrayList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(currentList == 2){
                    currentList = -1 ;
                }
                currentList = currentList + 1;
                imageModelArrayList = populateList(currentList);
                adapter = new Adapter(MainActivity.this,imageModelArrayList);
                recyclerView.setAdapter(adapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    private ArrayList<Model> populateList(int number){

        ArrayList<Model> list = new ArrayList<>();

        for(int i = 0; i < 8; i++){
            Model imageModel = new Model();
            if(number == 0) {
                imageModel.setName(firstList[i]);
            }else if (number == 1){
                imageModel.setName(secondList[i]);
            }else if (number == 2){
                imageModel.setName(thirddList[i]);
            }
            list.add(imageModel);
        }

        return list;
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }


    }

}

More Details on Main File

First of all, see the below

 private RecyclerView recyclerView;
    private ArrayList<Model> imageModelArrayList;
    private Adapter adapter;
    private int currentList = 0;
    private SwipeRefreshLayout mSwipeRefreshLayout;

First line is the object of RecyclerView class. Second is the arraylist with the object of the Model.java class.

Third line is the object of the Adapter class. Fourth one is integer variable.

Fifth is the object of the SwipeRefreshLayout class.

Now read the below lines

 private String[] firstList = new String[]{"Benz", "Bike",
            "Car","Carrera"
            ,"Ferrari","Harly",
            "Lamborghini","Silver"};
    private String[] secondList = new String[]{"Roger", "Rafael",
            "Novak","Maria"
            ,"Serena","Andy",
            "Agasi","Tsitsipas"};
    private String[] thirddList = new String[]{"India", "USA",
            "Canada","Australia"
            ,"Singapore","Japan",
            "UK","France"};

You can see that there are three string arrays are there.

All three includes the names of vehicles,players and countries respectively.

We will use all these three lists to set in the recycler view.

You can see the below lines in the onCreate() method.

 imageModelArrayList = populateList(currentList);

Above line is populating the data inside the imageModelArrayList using populateList() method.

Below are the code lines for populateList() method.

private ArrayList<Model> populateList(int number){

        ArrayList<Model> list = new ArrayList<>();

        for(int i = 0; i < 8; i++){
            Model imageModel = new Model();
            if(number == 0) {
                imageModel.setName(firstList[i]);
            }else if (number == 1){
                imageModel.setName(secondList[i]);
            }else if (number == 2){
                imageModel.setName(thirddList[i]);
            }
            list.add(imageModel);
        }

        return list;
    }

This method will get one integer value inside it’s parameter (int number). This integer value is defining which names recyclerview should display.

If it’s value is 0 then compiler will display vehicle names, for the value 1, it will display player names and for value 2 it will display country names in the recyclerview.

Now read the following source code snippet

  mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(currentList == 2){
                    currentList = -1 ;
                }
                currentList = currentList + 1;
                imageModelArrayList = populateList(currentList);
                adapter = new Adapter(MainActivity.this,imageModelArrayList);
                recyclerView.setAdapter(adapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

When the user pull or swipe down the recyclerview, compiler will run the above lines.

Here, compiler will check the value of the integer variable currentList.

If it’s value is 2 then it will set the value of currentList as -1

Then it will increment the value of currentList by 1.

After this, compiler will run the populateList() method to put data inside imageModelArrayList.

Then it will simply attach the adapter to the recycler view.

So it is all about our swipe to refresh recyclerview android example tutorial.

Swipe Down to Refresh ListView

If you want to create listview with swipe or pull down to refresh feature then read below

https://demonuts.com/pull-to-refresh-listview-android/

Download Code For Swipe To Refresh RecyclerView Android Example

Click to download Code From Github