Add Pull To Refresh to your Android app using Kotlin

Add Pull To Refresh to your Android app using Kotlin

Pull to Refresh is a gesture that is being used in a lot of popular apps, apps where content updates are frequent, like news, social media e.t.c.

In Android development this gesture it’s called ‘Swipe to Refresh‘.

Twitter uses Pull To Refresh to update user’s timeline

Add Pull To Refresh to our app

First, in our layout where includes the RecyclerView already, we’re gonna change the parent layout to LinearLayout and add the orientation to vertical (or you can use ConstraintLayout).

Next, we going to add the SwipeRefreshLayout, this adds the pull to refresh gesture, and inside that, we’re adding our RecyclerView, just like that:

After our layout is ready, let’s go to our file where our RecyclerView lives, in this example it’s in MainActivity.kt, and set the Color Scheme for our Pull To Refresh icon.

Also, we’re gonna set the setOnRefreshListener listener, where triggers every time we pull it down.

Inside in the setOnRefreshListener listener what we do is:

  • Clean our array from the previous data (line 24)
  • Call backend to download the data again. In our example, it just creates a list of numbers (line 25)
  • Pass the adapter to RecyclerView’s adapter (lines 26 – 27)
  • Stop Pull-To-Refresh animation (line 28)

…and done!

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

Notify of

Follow me