Android Pull To Refresh View using SwipeRefreshLayout

Android support library android.support.v4 provides support for in-built Android Pull To Refresh View using SwipeRefreshLayout. SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture.

Activities having SwipeRefreshLayout view should add OnRefreshListener to be notified whenever the swipe to refresh gesture is completed.

SwipeRefreshLayout.OnRefreshListener – Classes that wish to be notified when the swipe gesture correctly triggers a refresh should implement this interface.

Commonly Used Methods

isRefreshing () – returns whether the SwipeRefreshWidget is actively showing refresh progress.

setColorSchemeColors (int... colors) – Used to set the colors used in the progress animation.

setDistanceToTriggerSync (int distance) – Used to set the distance to trigger a sync in dips

setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener) – Set the listener to be notified when a refresh is triggered via the swipe gesture.

setRefreshing (boolean refreshing) – Notify the widget that refresh state has changed. Do not call this when refresh is triggered by a swipe gesture.

Sample Android Application with Android Pull To Refresh View using SwipeRefreshLayout

Application main activity layout will have android.support.v4.widget.SwipeRefreshLayout as parent view. SwipeRefreshLayout can have only one child similar to ScrollView. Add ListView whose items will be refreshed on swiping. Final /res/layout/activity_main.xml will be as below.

ListView item layout will be a simple TextView which will display name of the city. Create layout file /res/layout/list_item.xml as below.

Application main activity will implement OnRefreshListener to be notified for swipe gesture event completion. We will use simple ArrayList adapter to show city names in list view. Whenever onRefresh() receives call, we will set swipe view to refreshing and send message to Handler for updating city list. After updating adapter, we will set refreshing animation to false. I have used android.view.View.postDelayed(Runnable action, long delayMillis) for setting refreshing animation as it is called very early after receiving onRefresh() call. Final source code for MainActivity.java will be as below.

You may also like...

Leave a Reply

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