Material Design Topics

Pull To Refresh ListView & RecyclerView Example In Android Studio – SwipeRefreshLayout

In Android app Pull To Refresh aka SwipeRefreshLayout is used whenever we need to refresh the content’s of a view via a vertical swipe gesture. It accepts only one child means the component we want to refresh. It uses the listener mechanism to inform the listener who holds this component that a refresh event has occurred.

Basic Swipe Refresh Layout Example - Pull to RefreshThe Activity which instantiates SwipeRefreshLayout view should add an OnRefreshListener to be notified when the swipe to refresh gesture is completed. The Activity is responsible to handle the refresh event and refreshing the View. If the listener determines that there should not be a refresh then it must call setRefreshing(false) to cancel the visual indication of a refresh. If an Activity wished to show a progress animation then it should call setRefreshing(true) method to enable the gesture and progress animation.

Implementing a pull to refresh is very easy in Android. Whenever we need to detect the swipe down on any view, just wrap the view around SwipeRefreshLayout element.


Need of Pull To Refresh/SwipeRefreshLayout In Android:

Now a days lot of Android Apps like Google+, twitter etc provides an option to swipe or pull down to refresh the content of the page. When we swipe from top to down a loader will be displayed and will disappears once the new content is loaded.

Earlier we used to implement a custom swipe view to detect the swipe down but now android have made our work easier by introducing SwipeRefreshLayout in android.support.v4 to detect the vertical swipe on any view. It is mainly used with ListView or RecyclerView where we have a list of data fetched from server and we need to refresh it to get new records.


Basic Pull To Refresh / SwipeRefreshLayout XML code:

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

        < Add View's Here..../>

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


Example 1: Basic Example Of Pull To Refresh In Android Studio:

Below is the first example of SwipeRefreshLayout in which we display a random number in our TextView. Firstly we declare a SwipeRefreshLayout and a TextView in our XML file then get the reference of both in our Activity. After that we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we generate a random number and display it in our TextView.

Below you can download code, see final output and step by step explanation of the basic Pull To refresh example.

Download Code

Basic Swipe Refresh Layout Example - Pull to RefreshStep 1: Create A New Project And name It SwipeRefreshLayoutExample.

Step 2: Open Gradle Scripts > build.gradle and ensure support library is defined in it or not.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "abhiandroid.com.swiperefreshlayoutexample"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Step 3: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we create a SwipeRefreshLayout and two TextView’s in our XML file.

 <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simpleSwipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Random Number: "
            android:textColor="#000"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="20sp" />
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

Step 4:  Now open app -> java -> package -> MainActivity.java and add the below code.

In this step firstly we get the reference of SwipeRefreshLayout and TextView. After that we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we generate a random number and display it in our TextView.

package abhiandroid.com.swiperefreshlayoutexample;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    SwipeRefreshLayout swipeRefreshLayout;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // init SwipeRefreshLayout and TextView
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.simpleSwipeRefreshLayout);
        textView = (TextView) findViewById(R.id.textView);
        // implement setOnRefreshListener event on SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                // implement Handler to wait for 3 seconds and then update UI means update value of TextView
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // cancle the Visual indication of a refresh
                        swipeRefreshLayout.setRefreshing(false);
                        // Generate a random integer number
                        Random r = new Random();
                        int i1 = r.nextInt(80 - 65) + 65;
                        // set the number value in TextView
                        textView.setText(String.valueOf(i1));
                    }
                }, 3000);
            }
        });
    }
}

Output:

Now run the App and pull down to refresh the random number.

Example 2: Pull To Refresh with ListView In Android Studio:

Below is the second example of SwipeRefreshLayout with ListView in which we display list of Items and shuffle them on top to down swipe. Firstly we declare a SwipeRefreshLayout and a ListView in our XML file then get the reference of both in our Activity. After that we create a String type list of elements and then implement ArrayAdapter to set data in the list. Finally we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we shuffle the list items and set the adapter.

Below you can download code, see final output and step by step explanation of the Pull to refresh example with ListView.

Download Code

Swipe Refresh Layout With ListView Example Android StudioStep 1: Create A New Project And Name It SwipeRefreshLayoutExample.

Step 2: Open Gradle Scripts > build.gradle and ensure support library is defined in it or not.

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "abhiandroid.com.swiperefreshlayoutexample"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Step 3: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we create a SwipeRefreshLayout and a ListView in our XML file.

 <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simpleSwipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:padding="20dp">

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

Step 4: Now open app -> java -> package -> MainActivity.java and add the below code.

In this step firsly we get the reference of SwipeRefreshLayout and ListView. After that we create a String type list of elements and then implement ArrayAdapter to set data in the list. Finally we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we shuffle the list items and set the adapter..

 package abhiandroid.com.swiperefreshlayoutexample;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    SwipeRefreshLayout swipeRefreshLayout;
    ListView listView;
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("First Element", "Second Element", "Third Element", "Fourth Element", "Fifth Element"));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // init SwipeRefreshLayout and ListView
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.simpleSwipeRefreshLayout);
        listView = (ListView) findViewById(R.id.listView);
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);
        // implement setOnRefreshListener event on SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // cancel the Visual indication of a refresh
                swipeRefreshLayout.setRefreshing(false);
                shuffleItems();
            }
        });
    }

    public void shuffleItems() {
        // shuffle the ArrayList items and set the adapter
        Collections.shuffle(arrayList, new Random(System.currentTimeMillis()));
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);
    }
}

Output:

Now run the App and pull down to refresh the data in ListView.

Example 3: Pull To Refresh with RecyclerView In Android Studio:

Below is the example of SwipeRefreshLayout with RecyclerView in which we display list of Items and shuffle them on top to down swipe. Firstly we declare a SwipeRefreshLayout and a RecyclerView in our XML file then get the reference of both in our Activity. After that we create a String type list of elements and then implement RecyclerView Adapter to set data in the list. Finally we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we shuffle the list items and set the adapter.

Below you can download code, see final output and step by step explanation of the Pull to refresh example with RecyclerView.

Download Code

SwipeRefreshLayout With RecyclerView Example Android StudioStep 1: Create A New Project And Name It SwipeRefreshLayoutExample.

Step 2: Open Gradle Scripts > build.gradle and add RecyclerView Dependency and also ensure support library is defined in it or not.

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "abhiandroid.com.swiperefreshlayoutexample"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView
    testCompile 'junit:junit:4.12'
}

Step 3: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we create a SwipeRefreshLayout and a RecyclerView in our XML file.

 <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simpleSwipeRefreshLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>

Step 4: Create a new XML file rowlayout.xml for item of RecyclerView and paste the following code in it.
In this step we create a new xml file for item row in which we creates a TextView and ImageView to show the data.

 <?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="wrap_content"
    android:orientation="horizontal"
    android:padding="5dp">
    <!--
    items for a single row of RecyclerView
    -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher" />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        android:text="ABCD"
        android:textColor="#000"
        android:textSize="20sp" />
</LinearLayout>

Step 5: Now open app -> java -> package -> MainActivity.java and add the below code.

In this step firsly we get the reference of SwipeRefreshLayout and RecyclerView. After that we creates two ArrayList‘s for Person Names and then we set a LayoutManager and finally we set the Adapter to show the items in RecyclerView. Finally we implement setOnRefreshListener event on SwipeRefreshLayout and in onRefresh() method we shuffle the list items and set the adapter.

 package abhiandroid.com.swiperefreshlayoutexample;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    SwipeRefreshLayout swipeRefreshLayout;
    RecyclerView recyclerView;
    // ArrayList for person names
    ArrayList personNames = new ArrayList<>(Arrays.asList("Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6", "Person 7", "Person 8", "Person 9", "Person 10", "Person 11", "Person 12", "Person 13", "Person 14"));
    ArrayList personImages = new ArrayList<>(Arrays.asList(R.drawable.person1, R.drawable.person2, R.drawable.person3, R.drawable.person4, R.drawable.person5, R.drawable.person6, R.drawable.person7, R.drawable.person1, R.drawable.person2, R.drawable.person3, R.drawable.person4, R.drawable.person5, R.drawable.person6, R.drawable.person7));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // init SwipeRefreshLayout and ListView
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.simpleSwipeRefreshLayout);
        // get the reference of RecyclerView
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        // set a LinearLayoutManager with default vertical orientation
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        // call the constructor of CustomAdapter to send the reference and data to Adapter
        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, personNames, personImages);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
        // implement setOnRefreshListener event on SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // cancel the Visual indication of a refresh
                swipeRefreshLayout.setRefreshing(false);
                shuffleItems();
            }
        });
    }

    public void shuffleItems() {
        // shuffle the ArrayList's items and set the adapter
        Collections.shuffle(personNames, new Random(System.currentTimeMillis()));
        Collections.shuffle(personImages, new Random(System.currentTimeMillis()));
        // call the constructor of CustomAdapter to send the reference and data to Adapter
        CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, personNames, personImages);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
    }
}

Step 6: Create a new class CustomAdapter.java inside package and add the following code.

In this step we create a CustomAdapter class and extends RecyclerView.Adapter class with View Holder in it. After that we implement the overrided methods and create a constructor for getting the data from Activity. In this custom Adapter two methods are more important first is onCreateViewHolder in which we inflate the layout item xml and pass it to View Holder and other is onBindViewHolder in which we set the data in the view’s with the help of View Holder. Finally we implement the setOnClickListener event on itemview and on click of item we display the name of the person with the help of Toast.

 package abhiandroid.com.recyclerviewexample;
 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 android.widget.Toast;
 import java.util.ArrayList;
 public class CustomAdapter extends RecyclerView.Adapter {
 ArrayList personNames;
 ArrayList personImages;
 Context context;
 public CustomAdapter(Context context, ArrayList personNames, ArrayList personImages) {
 this.context = context;
 this.personNames = personNames;
 this.personImages = personImages;
 }
 @Override
 public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
 // infalte the item Layout
 View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
 // set the view's size, margins, paddings and layout parameters
 MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
 return vh;
 }
 @Override
 public void onBindViewHolder(MyViewHolder holder, final int position) {
 // set the data in items
 holder.name.setText(personNames.get(position));
 holder.image.setImageResource(personImages.get(position));
 // implement setOnClickListener event on item view.
 holder.itemView.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
 // display a toast with person name on item click
 Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show();
 }
 });
 }
 @Override
 public int getItemCount() {
 return personNames.size();
 }
 public class MyViewHolder extends RecyclerView.ViewHolder {
 // init the item view's
 TextView name;
 ImageView image;
 public MyViewHolder(View itemView) {
 super(itemView);
 // get the reference of item view's
 name = (TextView) itemView.findViewById(R.id.name);
 image = (ImageView) itemView.findViewById(R.id.image);
 }
 }
 }

Output:

Now run the App and pull down to refresh the content in RecyclerView.

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!

Download Free - Master Android App Development Sidebar

Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

Android Developer Facebook Group Free

Premium Project Source Code:




Download This FREE eBook

This free eBook will help you master the learning of Android Material Design in Android Studio!
close-link

See How AbhiAndroid Step By Step Video Training Helps You Master Android App Development

Video Training - Unlock step by step video training with new content added regularly. Develop Android Apps.
Android App Source Code - Get amazing Ecommerce, Food Ordering and Ultimate WebView source code with documentation.
ENROLL NOW
close-link

With a very poor revenue from selling source code files or using Google AdSense, we need your help to survive this website. Please contribute any amount you can afford
Pay
* Terms & Conditions Apply
close-link