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.
First of all, add the dependency into the build.gradle
file:
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
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>
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() }
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)
Note that upon successful reload, we must also signal that the refresh has completed by calling:
swipeRefreshLayout.isRefreshing = false
This is everything you need to do to make your app use the Pull to Refresh and refresh the content for your users!
Top comments (0)