Android SwipeRefresh Layout - Androhub

SwipeRefresh Layout

Android SwipeRefresh Layout

You might have noticed that lot of android apps like Twitter, Google+ provides an option to swipe / pull down to refresh it’s content. Whenever user swipes down from top, a loader will be shown and will disappear once the new content is loaded. In this tutorial we are going to learn how to provide the same option to your apps too.

Previously we used to implement a custom swipe view to detect the swipe down. But android made our day easier by introducing SwipeRefreshLayout in android.support.v4 to detect the vertical swipe on any view.

Methods of SwipeRefresh are quite few:

setOnRefreshListener(OnRefreshListener): adds a listener to let other parts of the code know when refreshing begins.
setRefreshing(boolean): enables or disables progress visibility.
isRefreshing(): checks whether the view is refreshing.
setColorScheme(): it receive four different colors that will be used to colorize the animation.

Example

In this tutorial, we are going to learn how to use Swipe Down Refresh Layout.

VIDEO DEMO

In last tutorial  we learned about RecyclerView. So i am going to use the same tutorial for SwipeRefresh. You can check RecyclerView tutorial here.

1. Android SwipeRefreshLayout

Implementing SwipeRefreshLayout is very easy. Whenever you want to detect the swipe down on any view, just the wrap the view around SwipeRefreshLayout element. In our case, we are going to use it with RecyclerView. And implement your activity class from SwipeRefreshLayout.OnRefreshListener. When user swipes down the view, onRefresh() method will be triggered. In you need to take appropriate action in that function like making an http call and fetch the latest data.

2. SwipeRefreshLayout Code

  • First find the id of Swipe View.
  • Set the color schemes for refresh view circular bar.
  • Finally set the refresh listener for refreshing view. In onRefresh() you can call the refreshing method to refresh view.

3. Refresh Code

Here you can see that i am using a handler so that refresh view should be visible for that because i am populating adapter from local data and it won’t take too long but if you are fetching data from server then you don’t need to use handler.

There is RandomGenerator() method that i used in last RecyclerView tutorial. This method will return random numbers between 0-9.

Finally after refreshing adapter we have to setRefreshing(false);

4. Source Code

The rest of the code is same as RecyclerView tutorial by adding this RefreshView Code.

Finally you are all done. Now, you can use swipe refresh into your app to refresh ListView, GridView and RecyclerView. This is easy to implement in minimum number of lines.

Thanks. :)

 

Post comment

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