Next lesson playing in 5 seconds

  • Overview
  • Transcript

2.7 Implement the Swipe-to-Refresh Gesture

Pressing a button to refresh the contents of the screen is out of fashion. Most users today prefer swiping instead. In this lesson, you'll learn how to use the SwipeRefreshLayout to implement a swipe-to-refresh gesture.

2.7 Implement the Swipe-to-Refresh Gesture

Hello and welcome back. In this lesson, I'll show you how to create a swipe gesture that can refresh the contents of the recycler view. The swipe to refresh gesture is very popular and most Android users know how to use it. Nevertheless, for the sake of accessibility, we will also keep this refresh menu button. Let's start by going to the layout file of the main activity and switching to the text mode. Above the RecyclerView add a SwipeRefreshLayout widget. Set its width and height to match_parent. Next, cut the RecyclerView tag and paste it inside to SwipeRefreshLayout tag. You must now move all the layout related attributes of the RecyclerView to the sSipeRefreshLayout, so that the position of the RecyclerView is not affected. So, we have two attributes here. Finally, give an ID to the SwipeRefreshLayout. Call it swipe. Go to the main activity class now and add the SwipeRefreshLayout as a member variable. And as always, initialize it inside the onCreate method using findViewByID Next, towards the end of the onCreate method add a new onRefreshListener to the SwipeRefreshLayout using the setOnRefreshlistener method. Inside the onRefresh method, all you need to do is call, updateScreen. The SwipeRefreshLayout allows you to display a loading indicator while the refresh is in progress. However, you have to turn the indicator on and off manually yourself. So, inside the updateScreen method, lets turn the indicator on by calling the setRefreshing method. And passing true to it. And then at the end of the renderList method Turn the indicator off by passing false to the setRefreshing method. Our SwipeRefreshLayout is ready. If you run the app you will not see any difference right away. But if you swipe from the top of the screen, you will see this refreshing indicator. You must pull it about halfway down the screen and then release it. Once you do so, the refresh starts. And after the refresh is complete, the indicator disappears. You will now see the loading indicator even when you use the navigation view to switch to a different StackExchange site. You now know how to implement the swipe to refresh gesture. Thanks for watching.

Back to the top