Android Swipe Down to Refresh a Layout Example

By Android Swipe Down to Refresh a Layout Example

Hello buddy,

In this tutorial, we are discussing the android SwipeRefreshLayout. This enables an android app user to swipe or pull down to refresh the contents of the screen. You might have seen that apps like Twitter and Facebook offer an option to swipe down to refresh tweets and posts. Once a user pulls down from the top, a loader appears and will disappear after new content has been fetched. In this article, we are going to implement the same option for our app.

Before the introduction of SwipeRefreshLayout in android.support.v4, android programmers used to implement their custom swipe view, let’s say a ListView, to listen to swipe down actions. SwipeRefreshLayout can detect vertical swipe on every view, thanks to android. Its basic need is to enable users to refresh a screen manually. 

The class has a vital listener called OnRefreshListener. When swiping down this listener is triggered and calls the OnRefresh() method. The programmer needs to override this method to suit his/her need.

Now let us develop an application together for better understanding. This app consists of a ListView that on swipe down will refresh the screen and displays random list rows.

Implementing SwipeRefreshLayout

It is very easy to implement this in your application. But first things first, let us create a new android project using Android Studio.

  1. In Android Studio, create a new project called SwipeToRefreshApp and select an Empty Activity and proceed. 
  2. Open build.grandle file found in the app folder and ensure appcompact library dependency is there
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:29.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

Activity Main xml

Now open activity_main.xml located under layout in res folder. The following is the content of this file.

<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/pullToRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> <ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"> </ListView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>   

We added a ListView inside SwipeRefreshLayout.

Main Activity Java

Now open MainActivity.java located under java folder. The following is the content of this file.

package com.example.swipetorefreshapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
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 {
    ArrayList arrayList = new ArrayList();
    SwipeRefreshLayout pullToRefresh;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pullToRefresh = findViewById(R.id.pullToRefresh);
        listView = findViewById(R.id.listView);
        String [] companies = {"Google", "YouTube", "FaceBook", "Twitter", "Instagram", "Microsoft",
                "Quora", "Eric Muchenah", "Apple", "Samsaung"};
        arrayList.addAll(Arrays.asList(companies));
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);
        pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                shuffle();
                pullToRefresh.setRefreshing(false);
            }
        });
    }
    public void shuffle(){
        Collections.shuffle(arrayList, new Random(System.currentTimeMillis()));
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);
    }
}
  1. In the code above, we have created an ArrayList of Strings (companies) that we will add to the ArrayAdaptor object.
  2. We have created an ArrayAdaptor that later we will set the object on the ListView.
  3. We have set a listener on our SwipeRefreshLayout and implement the onRefresh() method.
  4. We have added a shuffle() method inside onRefresh() hence whenever a user swipes down the list will be shuffled.
  5. We have used Java Collections to shuffle the ArrayList randomly by setting a random seed as the current time in milliseconds.
  6. We have included setRefreshing(false). This notifies the SwipeRefreshLayout instance that refreshing is completed and the refreshing loader animation must be stopped.

Run the project and test it. You should able see the swipe refresh animation on app launch and list view updated each time you swipe down it.



Read this book, Head First Android Development: A Brain-Friendly Guide 1st Edition by Dawn Griffiths, to learn setting up your IDE to creating fully functioning apps.

This brings us to the end of this article. Thanks for your time and happy coding!

Was this article helpful?

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.

Never miss an Article from this Blog

Get Programming and Technology Tips for Beginners by subscribing now.