Fast Smooth Scroll to Top

A common UX pattern relating to lists is the ability to quickly jump to the top of the list. Whether it be tapping the toolbar, the tab you’re currently on, or some other UI element, this convenient pattern is seen almost everywhere there’s a list. If you’re using a RecyclerView, jumping straight to the top using scrollToPosition can be quite jarring and doesn’t feel smooth, and smoothScrollToPosition can take forever if you’re in a huge list.

One way to provide a smooth experience for your users is to use both methods. First, checking if the user is beyond a certain position and if so, jumping to a preset position with scrollToPosition, and then after that, calling smoothScrollToPosition(0). An example extension function for RecyclerViews might look like this:

fun RecyclerView.scrollToTop() {
    (layoutManager as? LinearLayoutManager)?.let { lm ->
        if (adapter?.itemCount ?: 0 > 10 && lm.findFirstVisibleItemPosition() > 10) {
            scrollToPosition(10)
        }
    }
    smoothScrollToPosition(0)
}

In this example, if the first visible item is greater than position 10, we jump to position 10, then smooth scroll to position zero. The end result is that the user sees a smooth scroll, regardless of where they are in the list, and the smooth scroll itself takes at most a short amount of time. Note that this assumes your layout manager is a LinearLayoutManager; you may have to use different visibility methods or behaviors if you’re using any different type.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s