DEV Community

Douglas Fornaro
Douglas Fornaro

Posted on

3 2

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!

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay