Android Swipe Refresh Layout Example

SwipeRefreshLayout is used to implement drop-down refresh effect in android. It commonly used with ListView, RecyclerView or ScrollView etc. The view object should be scrollable and should be the only child component under it.

When you pull down the screen to a certain height from screen top, it will show the refresh indicator. If the pull down height is not enough, it will be recovered. During the refreshing process, if you continue to pull down, the screen will not response, that means the drop-down event is blocked when refreshing.

1. SwipeRefreshLayout Methods Introduction.

  1. isRefreshing(): Return whether the layout control is refreshing or not.
  2. setColorSchemeResources(int… colorResIds): Set refresh indicator colors, each indicator roll will show a different color in the input color array.
  3. setProgressBackgroundColorSchemeResource(int colorRes): Set refresh indicator background color.
  4. setRefreshing(boolean refreshing): True means just refreshing will show the refresh indicator, false means not refreshing will hide the refresh indicator.

2. SwipeRefreshLayout Example.

In this example, when you pull down the ListView, the refresh indicator will be shown. After child thread read more data from server ( each refresh will add 10 list items at the ListView beginning), it will send message to activity main thread to let it update the ListView content and hide the refresh indicator.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/xCrPjIZ9P3Y

3. Main Activity.

SwipeRefreshLayoutActivity.java

package com.dev2qa.example.material_design.swipe_refresh_layout;

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

import com.dev2qa.example.R;

import java.util.ArrayList;
import java.util.List;

public class SwipeRefreshLayoutActivity extends AppCompatActivity {

    private ListView listView = null;

    private List<String> dataList = null;

    private ArrayAdapter<String> listDataAdapter = null;

    // This handler is used to update activity UI components/
    private Handler uiHandler = null;

    // This message means update list view. 
    private int MESSAGE_UPDATE_LIST_VIEW = 1;

    private SwipeRefreshLayout swipeRefreshLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe_refresh_layout);

        setTitle("dev2qa.com - Android Swipe Refresh Layout Example.");

        // Initialize ui controls.
        initControls();

        // When swipe refresh layout refresh.
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Refresh list view data.
                refreshListView();
            }
        });
    }


    private void initControls()
    {
        if(listView==null)
        {
            listView = (ListView)findViewById(R.id.swipe_refresh_layout_list_view);

            dataList = new ArrayList<String>();
            for(int i=0;i<10;i++)
            {
                dataList.add("List item " + (i + 1));
            }

            listDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
            listView.setAdapter(listDataAdapter);
        }

        if(swipeRefreshLayout == null)
        {
            // Get swipe refresh layout object.
            swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);
            // Set refresh indicator background color to green.
            swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorCyan);
            // Set refresh indicator color to red.
            int indicatorColorArr[] = {R.color.colorRed, R.color.colorGreen, R.color.colorOrange};
            swipeRefreshLayout.setColorSchemeResources(indicatorColorArr);
        }

        if(uiHandler == null)
        {
            uiHandler = new Handler()
            {
                @Override
                public void handleMessage(Message msg) {
                    // If the message want to refresh list view.
                    if(msg.what == MESSAGE_UPDATE_LIST_VIEW)
                    {
                        // Refresh list view after add item data.
                        listDataAdapter.notifyDataSetChanged();
                    }
                    // Stop showing the swipe refresh layout.
                    swipeRefreshLayout.setRefreshing(false);
                }
            };
        }
    }

    /* This method emulate read more data from server in child thread.
       Each swipe refresh will add 10 list items. */
    private void refreshListView()
    {
        Thread thread = new Thread()
        {
            @Override
            public void run() {
                try
                {
                    // Emulate read data from server which will cost some times.
                    Thread.sleep(3000);

                    int size = dataList.size();

                    // Add 10 list items for each swipe refresh.
                    for(int i=size;i<(size + 10);i++)
                    {
                        // Add new list item at the beginning of the list to show effect more clearly.
                        dataList.add(i - size, "List item " + (i + 1));
                    }

                    // Create a message object.
                    Message message = new Message();
                    // Set message purpose.
                    message.what = MESSAGE_UPDATE_LIST_VIEW;
                    // Send the message to main thread Handler to process.
                    uiHandler.sendMessage(message);

                }catch(InterruptedException ex)
                {
                    ex.printStackTrace();
                }
            }
        };

        thread.start();
    }

}

4. Activity Layout Xml File.

activity_swipe_refresh_layout.xml

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

    <ListView
        android:id="@+id/swipe_refresh_layout_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="2dp"
        android:divider="@color/colorBlue"/>

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

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.