How to add Scroll To Top in RecyclerView in Android using Kotlin
- January 28, 2020
- John Codeos
In this tutorial, I’m going to show you how to implement Scroll To Top in your RecyclerView in two ways.
First, by pressing the Activity’s title, and second, by pressing a button when it appears while you scroll down.
Adding Scroll To Top in Activity’s Title
First, we need to replace the ActionBar with our own Toolbar that can handle taps.
Go to your style.xml file (res > values > style.xml), and add a theme with No Action Bar.
Don’t forget to change the theme of your Activity on the AndroidManifest.xml too.
To be able to show our own Toolbar at the top of the Activity correctly, we are going to use the CoordinatorLayout.
Add the following dependency in your build.gradle if you don’t already have it.
Go to your Activity‘s layout and put your RecyclerView inside a CoordinatorLayout.
Between the CoordinatorLayout and your RecyclerView, add a RelativeLayout and set the layout behavior
Without this attribute, the RecyclerView will be behind the Toolbar.
If you get the error
Cannot resolve symbol '@string/appbar_scrolling_view_behavior'
Go to your build.gradle of your app and add the following dependency.
Back in the Activity‘s layout, add an AppBarLayout above your RelativeLayout
Inside the AppBarLayout add a Toolbar
Last, add a TextView inside the Toolbar, like that:
So at the end, will look like this:
Now, go to your Activity‘s file, customize your TextView and add a click listener to scroll to the top of the RecyclerView every time we tap the TextView.
Adding Scroll To Top in Button
This method is very common when you create a chat. The user scrolls to see the chat history and a button with an arrow appears to scroll back.
First, add the following dependency in your build.gradle of your app, if you want to have a circular shape button(ImageView) for the Scroll To Top icon later.
Then, in the layout of your Activity, add the Scroll To Top button(ImageView) outside the screen.
Now, in your Activity file
Add the positions for the button where do you want to be when it’s visible and hidden
Add to the button a click listener, so when we tap it, it will scroll to the top.
Also, we need to hide the arrow button so it’s not visible when the Activity starts.
Add a scroll listener in your RecyclerView to detect when we scroll to the bottom, to show the arrow.
In this example, we say that we want to show the arrow when the 12th item from the RecyclerView appears on screen while we scroll.
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!