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.
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.