[SOLVED] RecyclerView: scrollToPosition not working

05Oct, 2019

Sometimes when working on an android app, you might need to programmatically scroll a RecyclerView to a position.  For example a chat screen.  That’s when the recyclerView.scrollToPosition() method comes in.

However, this method sometimes does not work and will simply do nothing.

Cause

The are several reasons that can cause the scrollToPosition() method to not work, however I will describe just one of the reasons in this post

Setting layoutManager.setReverseLayout(true)

According to the docs here:

Used to reverse item traversal and layout order. This behaves similar to the layout change for RTL views. When set to true, first item is laid out at the end of the UI, second item is laid out before it etc. For horizontal layouts, it depends on the layout direction. When set to true, If RecyclerView is LTR, than it will layout from RTL, if RecyclerView} is RTL, it will layout from LTR. If you are looking for the exact same behavior of setStackFromBottom(boolean), use setStackFromEnd(boolean)

So basically, when you reverse the RecyclerView’s layout, the indexes of the RecyclerView also reverses.

Solution

The solution depends on the exact cause of the problem.

  • If the cause is due to setReverseLayout(true) being set, then you can easily solve the problem by simply making sure that the index you pass to recyclerView.scrollToPosition() is not greater than the list size – 1.Also, if you are trying to scroll to the end of the list, you should pass 0 to the scrollToPosition() method instead of the length of the list – 1.
  • If the cause of the issue is unknown, then this solution is for you.Up till now,  I have not had the time to debug the RecyclerView class in order to figure out why this method fails at times, however, the RecyclerView.smoothScrollToPosition(position); method seems to always work in all scenarios.

And that’s all for now.

If you have any questions or contributions, feel free to post them in the comment box below


1 Comment

  • Daniel November 16, 2019 @ 2:56 pm

    It should work as expected right? Afterall, scrolling an item to certain position is a fairly common usage. Yet, why does this question is still popular?

Leave a Reply

Your email address will not be published. Required fields are marked *