SwipeRefreshLayout

SwipeRefreshLayout provides the ability to refresh the content of a view using a vertical swipe gesture.

Add dependency

implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")

SwipeRefreshLayout is used as parent element for RecyclerView, ListView or GridView.

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list"
        >
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

Use setRefreshing() method to show or hide the progress indicator.

Use the setOnRefreshListener() method to set a handler for the swipe gesture.

mySwipeRefreshLayout.setOnRefreshListener {
        // Do not call this when refresh is triggered by a swipe gesture. 
        // mySwipeRefreshLayout.isRefreshing = true
		
        // invoke actual data-refresh operation in background
        // set mySwipeRefreshLayout.isRefreshing = false when operation finished
        myUpdateOperation()
}

refresh action

You can add refresh action to your app's action bar to ensure that users who may not be able to perform a swipe gesture can still trigger a manual update.

You should add the refresh action as a menu item, rather than as a button, by setting the attribute android:showAsAction=never.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/menu_refresh"
        android:showAsAction="never"
        android:title="@string/menu_refresh"/>
</menu>

Then handle the request action

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {

        // Check if user triggered a refresh:
        R.id.menu_refresh -> {
         
            // Signal SwipeRefreshLayout to start the progress indicator
            mySwipeRefreshLayout.isRefreshing = true

            // Start the refresh background task.
            myUpdateOperation()

            return true
        }
    }

    // User didn't trigger a refresh, let the superclass handle this action
    return super.onOptionsItemSelected(item)
}