Pull to refresh in Android

douglascf

Douglas Fornaro

Posted on March 28, 2021

Pull to refresh in Android

Pull to refresh is a gesture that the user can make to update the screen, such as reloading the feed for Instagram or Twitter.

Let's see in this article how to built Pull to Refresh for Android.

Pull to refresh

First of all, add the dependency into the build.gradle file:

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
Enter fullscreen mode Exit fullscreen mode

Add your RecyclerView or other content inside the SwipeRefreshLayout.

The SwipeRefreshLayout is a ViewGroup that can hold only one scrollable view as a child. This can be either a ScrollView or a RecyclerView.

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

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

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Enter fullscreen mode Exit fullscreen mode

Next, let's implement the refresh listener on our Activity/Fragment that will be notified when the swipe gesture is completed.

swipeRefreshLayout.setOnRefreshListener { viewModel.loadContent() }
Enter fullscreen mode Exit fullscreen mode

It's possible to configure the colors been shown during the load:

swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light)
Enter fullscreen mode Exit fullscreen mode

Note that upon successful reload, we must also signal that the refresh has completed by calling:

swipeRefreshLayout.isRefreshing = false
Enter fullscreen mode Exit fullscreen mode

This is everything you need to do to make your app use the Pull to Refresh and refresh the content for your users!

💖 💪 🙅 🚩
douglascf
Douglas Fornaro

Posted on March 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related