Pull to Refresh with ListView in Android with Example
The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. It uses a vertical swipe gesture to refresh the content of the views. SwipeRefreshLayout widget detects the vertical swipe and display distinct progress bars and triggers the callback methods in the app. To use this behavior SwipeRefreshLayout widget must be the parent of ListView or GridView. This behavior of the SwipeRefreshLayout widget gives the user to refresh the layout manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs.
Swipe-to-Refresh ListView is very much similar to Swipe-to-Refresh RecyclerView. In place of ListView, we use RecyclerView. Please refer to Pull to Refresh with RecyclerView in Android with Example.
In this example, we would store data of string type into the ArrayList which is used for populating the ListView. Whenever OnRefresh() method is called ArrayList data gets shuffled. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
We are using SwipeRefreshLayout. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency you need to click on Sync Now.
Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.
Step 3: Working with the activity_main.xml file
In this step, we will create SwipeRefreshLayout and add ListView to it. Go to app > res > layout > activity_main.xml and add the following code snippet.
Step 4: Working with the MainActivity.java file
In this step, we get the reference of SwipeRefreshLayout and ListView which we define in our activiy_main.xml layout file. We will create an ArrayList of string elements and implement ArrayAdapter in order to set data to the list. And then, we implement setOnRefreshListener event on SwipeRefreshLayout and call OnRefresh() method to shuffle the list elements.