If you are here then you might already be knowing what is Swipe To Refresh UI Pattern. But if you don’t, it is simple a UI element which allows users to manually trigger action of loading dynamic content in apps.
Swipe To Refresh is used by many biggies like Gmail, Inbox, Google Chrome, Twitter, Google+, Newsstand and much more. So today, we will see “How To Implement Swipe To Refresh Material Design UI Pattern In Android Using SwipeRefreshLayout”.

 

Why The Hell We Use Swipe To Refresh?

Good Question! 😀 According to the Android Guidelines, it is considered BAD if the user has to manually trigger refreshing or loading content process of the app. Such kind of tasks must be performed automatically using Sync Adapters. But, if the user wants to refresh the content in the app manually then he/she can use Swipe To Refresh Action by performing a swipe down gesture. Swipe To Refresh is simple, yet important implementation for any app with such needs.

 

If your content is local, then there is a way to update the UI automatically if any there is any change in the data. It is known as ContentObserver.
Check out: Use Android’s ContentObserver To React On Content Changes

 

Understanding Swipe To Refresh

Simply to make this work, we need to first add SwipeRefreshLayout to our Layout file. Then, we will create and initialize the SwipeRefreshLayout class’s object. Once done with initializing, we can set an OnRefreshListener to it which will perform the task to be done when the user performs the swipe down gesture.

 

Steps To Implement Swipe To Refresh

Step 1. Open Android Studio and create a new blank project by navigating to File => New Project and then fill other details.

Step 2. The first thing to be done is adding the dependencies. So open the build.gradle file and add the following line in dependencies.

compile 'com.android.support:support-v4:22.2.0'

So, my dependencies would look like as given below. I have also used the recycler view dependency to use RecyclerView in our demo.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
}

Step 3. Now open colors.xml in res => values directory. If it does not exists then create one with the same name. After opening the file, add colors resources as given below.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black">#000</color>
    <color name="white">#fff</color>
    <color name="red">#D50F25</color>
    <color name="yellow">#EEB211</color>
    <color name="green">#009925</color>
    <color name="blue">#3369E8</color>
</resources>

This colors will be used to customize the Swipe To Refresh Loader.

Step 4. Now, open your activity_main.xml file in res => layout directory and add the SwipeRefreshLayout to it as shown below.
Note: The SwipeRefreshLayout must have only one child view.

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipe_refresh_layout"
    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"
    tools:context=".MainActivity">

    <!--The SwipeRefreshLayout must only have one child view inside it-->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

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

Step 5. Now we need to create a layout resource file inside res => layout directory for RecyclerView’s Row called recycler_view_row.xml. After creating, add the following code as given below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:textColor="@color/black"
        android:id="@+id/time_textView"/>
</LinearLayout>

Step 6. Next, open the MainActivity.java file . Once opened initialize the SwipeRefreshLayout and then set OnRefreshListener to it as shown below. There are more methods for customizing the Swipe To Refresh Loader. They are also shown below.
Note: Do not panic seeing the length of code. Most of the stuff is for showing the demo and rest are comments for understanding. 😀

package com.androidsphere.swipetorefreshdemo;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class MainActivity extends ActionBarActivity {
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    //ArrayList will contain all the data for
    // recycler view to show
    ArrayList timings;
    MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Initialising some required views to
        // show SwipeToRefresh demo.
        initializeRecyclerView();

        //From Here Starts All The Swipe To
        // Refresh Initialisation And Setter Methods.
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);//Initialising
        //Setting Up OnRefresh Listener
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                //onRefresh method is used to perform all the action
                // when the swipe gesture is performed.
                try {
                    addTime();//addTime() Method is called
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //This are some optional methods for customizing
        // the colors and size of the loader.
        swipeRefreshLayout.setColorSchemeResources(
                R.color.blue,       //This method will rotate
                R.color.red,        //colors given to it when
                R.color.yellow,     //loader continues to
                R.color.green);     //refresh.

        //setSize() Method Sets The Size Of Loader
        swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);
        //Below Method Will set background color of Loader
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.white);
    }

    public void addTime() throws InterruptedException {
        //Here I am using a Handler to perform the refresh
        // action after some time to show some fake time
        // consuming task is being performed.
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //EveryTime when this method is called
                // time at that instant will be added to
                // the ArrayList. This is just to populate
                // the recycler view.
                myAdapter.timings.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
                myAdapter.notifyItemInserted(myAdapter.timings.size()-1);
                //setRefreshing(false) method is called to stop
                // the refreshing animation view.
                if(swipeRefreshLayout.isRefreshing())
                    swipeRefreshLayout.setRefreshing(false);
            }
        },4000);

    }

    public void initializeRecyclerView(){
        //All this setup is used for giving the demo.
        //You can skip this if you want.
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        timings = new ArrayList<>();
        //Giving initial value
        timings.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
            .format(new Date()));
        myAdapter = new MyAdapter(this,timings);
        recyclerView.setAdapter(myAdapter);
    }

}

 

Customizing Swipe To Refresh Loader

  1. setColorSchemeResources(int… colorResId): This method is used to give color resources which will be used for the rotating line inside the loader. We can pass as many parameters as we want. All these color resources will be used to timely change the color rotating line.
    Example: You can watch our demo in the video given above in this post.
  2. setSize(int size): This method is used to set the size of loader. We can pass two parameters, namely SwipeRefreshLayout.LARGE and SwipeRefreshLayout.DEFAULT.Swipe To Refresh Loaders Size
  3. setProgressBackgroundColorSchemeResource(int colorResId): This method is used to set the background color of loader.Swipe To Refresh Loaders Background Color

 

Step 7. Now, we have to create another class called MyAdapter.java. This class will be used by the RecyclerView in this demo. You can just skip this part if you want.

package com.androidsphere.swipetorefreshdemo;

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.TextView;
import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter{
    Context context;
    LayoutInflater inflater;
    ArrayList timings;
    MyAdapter(Context context,ArrayList timings){
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.timings = timings;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.recycler_view_row,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.timeTextView.setText(timings.get(position));
    }

    @Override
    public int getItemCount() {
        return timings.size();
    }
}
class MyViewHolder extends RecyclerView.ViewHolder{
    TextView timeTextView;
    public MyViewHolder(View itemView) {
        super(itemView);
        timeTextView = (TextView) itemView.findViewById(R.id.time_textView);
    }
}

Step 8. Now, we are ready to see our demo. Click on Run and here we go.

So, now you have learned a new Material Design UI Pattern that is Swipe To Refresh. So go on and implement it in your future apps.

Pin It on Pinterest

Liked it? Your Friends will also like it!

Share this post with your friends and spread the knowlegde.

Liked it? Your Friends will also like it!

Share this post with your friends and spread the knowledge!