Android SwipeRefreshLayout - Android Pull/Swipe Down to Refresh With Examples

In this tutorial we’ll discuss and implement Android Swipe Down to Refresh or Android Pull to Refresh the screen. This Android Material Design UI pattern is very commonly seen in many applications like Gmail, Facebook, Twitter and implemented using Android SwipeRefreshLayout.

Android SwipeRefreshLayout

android-swipe-pull-down-to-refresh
Android SwipeRefreshLayout is a ViewGroup that can hold only one scrollable child. It can be either a ScrollView, ListView or RecyclerView. The basic need for a SwipeRefreshLayout is to allow the users to refresh the screen manually. This is pretty common in the Facebook Newsfeed screen. Before this layout was available in the support library, we had to resort to creating and detecting custom swipe down gestures to refresh let’s say a ListView.

This class consists of one important listener that is OnRefreshListener. On swiping down this listener is triggered and the OnRefresh() method is called. We can override this method according to our needs.

In this tutorial we’ll develop an application that consists of a ListView that on swipe down, refreshes the screen and shuffles the list rows.

Android SwipeRefreshLayout Project Structure

android-swipe-to-refresh-project-structure

Android SwipeRefreshLayout Code

The activity_main.xml is given below.

We add a ListView inside a SwipeRefreshLayout in the layout as shown above.

The MainActivity.java class is given below.

  • In the above code we’ve created an ArrayList of strings and add it to the ArrayAdapter object that’s later set onto the ListView.
  • We’ve added a shuffle method that shuffles the whole ArrayList every time the onRefresh() is called.
  • We’ve used the Collections framework method to randomly shuffle the ArrayList by setting a random seed as the current time in milli seconds.
  • setRefreshing(false) is an important line of code. It notifies the SwipeRefreshLayout instance that the refreshing is completed and it should stop the refreshing loader animation.
  • The default refreshing animation color is set to black. We can change it using the method setColorSchemeResources()

The output of the application in action is given below.
android pull to refresh example

This brings an end to this tutorial. You can download the Android SwipeRefreshLayout project from the link below and play around with different ways you can refresh the android screen on pull down.

By admin

Leave a Reply