RecyclerView - How to smooth scroll to top of item on a certain position?

Tiago picture Tiago · Jul 5, 2015 · Viewed 111.3k times · Source

On a RecyclerView, I am able to suddenly scroll to the top of a selected item by using:

((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);

However, this abruptly moves the item to the top position. I want to move to the top of an item smoothly.

I've also tried:

recyclerView.smoothScrollToPosition(position);

but it does not work well as it does not move the item to the position selected to the top. It merely scrolls the list until the item on the position is visible.

Answer

Paul Woitaschek picture Paul Woitaschek · Apr 19, 2017

RecyclerView is designed to be extensible, so there is no need to subclass the LayoutManager (as droidev suggested) just to perform the scrolling.

Instead, just create a SmoothScroller with the preference SNAP_TO_START:

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
  @Override protected int getVerticalSnapPreference() {
    return LinearSmoothScroller.SNAP_TO_START;
  }
};

Now you set the position where you want to scroll to:

smoothScroller.setTargetPosition(position);

and pass that SmoothScroller to the LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);