Swipe To Refresh Layout – Android

In the latest revision of the android support library came out with an interesting new layout SwipeRefreshLayout which implements the famous pull-down-to-refresh pattern. In the following tutorial I will show you how to implement it with a ListView and avoid some pitfalls.

SwipeToRefresh

To use this new layout you will need to have at least the android support library with at least revision 19.1.

First we need to import the support library project to our workspace and then add it to your main project as a library.

 

Let’s Write Some Code

First we need to create a layout XML file:

Next step is to add some java code in your Activity or Fragment.

We are almost there, just a few more lines of code.
If you try to refresh, your will be able to see the animation and your list would be updated. However, if scroll down in your list and try to go up again the swipe to refresh would be triggered again and you won’t be able to go back to the top of your list. This is annoying. You don’t want an angry user. Here is a fix for that.

We force the layout to refresh only when the very first item of the list is fully visible. To do this we assign an OnScrollListener to our ListView after the initialization of our swipe to refresh layout.

Now you are ready.

Go forth and master the art of Swiping. 😀

4 Comments

  1. bdh February 22, 2015 at 10:36 am

    Hello tk,thanks!This works!how can i implement isRefreshing() method?

    1. bdh February 22, 2015 at 10:51 am

      And how can use AsyncTask instead of Runnable? Thanks in advanc!!

    2. kioko March 11, 2015 at 7:49 am

      Hi,

      Did you manage to use an AsyncTask? If not let me know and I will post a blog on it.

  2. akis March 13, 2015 at 11:55 am

    Excellent!

Leave a Reply to akis Cancel reply

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