SwipeRefreshLayout has been in the support library for quite some time. It is a standard (and probably the easiest) way to implement the common Pull to Refresh pattern in Android.
The SwipeRefreshLayout should be used whenever the user can refresh the contents of a view via a vertical swipe gesture. This layout should be made the parent of the view that will be refreshed as a result of the gesture and can only support one direct child. This view will also be made the target of the gesture and will be forced to match both the width and the height supplied in this layout.
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/itemsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</android.support.v4.widget.SwipeRefreshLayout>
The activity that instantiates this view should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again; the listener is responsible for correctly determining when to actually initiate a refresh of its content.
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Refresh items
refreshItems();
}
});
void refreshItems() {
// Load items
// ...
// Load complete
onItemsLoadComplete();
}
void onItemsLoadComplete() {
// Update the adapter and notify data set changed
// ...
// Stop refresh animation
mSwipeRefreshLayout.setRefreshing(false);
}
If at any point, you want to disable pull to refresh gestures and progress animations, call setEnabled(false)
on the view.
mSwipeRefreshLayout.setEnabled(false);
That’s all you need to add a Pull to Refresh to your app. Its already updated with material design, so it aligns well with other design components on Android.