Implement SwipeRefreshLayout in Android

You might have experienced SwipeRefreshLayout in the last few updates of Chrome browser. You need to swipe from top to halfway and one circle came down with arrow rotating in it. Once you swipe enough it will start refreshing the page and disappear once the page is updated.

It’s SwipeRefreshLayout provided in android-sdk support library v4. Now we see the implementation part for this.

First you have to wrap the element you want to swipe like if you want ListView, GridView or any other view to refresh on swipe, enclose it in SwipeRefreshLayout as below.

<android.support.v4.widget.SwipeRefreshLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/swipe_refresh_layout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp" />
</android.support.v4.widget.SwipeRefreshLayout>

Now from the the .java file make the following changes to implement it.

mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mList = (ListView) findViewById(R.id.list);

mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
  @Override
  public void onRefresh() {
    mSwipeRefreshLayout.setRefreshing(true);
    ( new Handler()).postDelayed(new Runnable() {
      @Override
      public void run() {
        mSwipeRefreshLayout.setRefreshing(false);
      }
    }, 3000);
  }
});

Please leave the comments if you find any problem in above code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s