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.
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
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
So basically, when you reverse the RecyclerView’s layout, the indexes of the RecyclerView also reverses.
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