How to get the Scrollposition in the Recyclerview/Layoutmanager?

Solution 1:

For future use, If you are switching between Fragments within the same activity and all you want to do is save scroll-position for recyclerview and then restore recyclerview to the same scroll-position, you can do as follows:

In your onStop()/onDestroyView()/onPause() whatever callback is more appropriate, do this:

Parcelable recylerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

And In your onStart()/onCreateView()/onResume() whatever callback is more appropriate, do this:

recyclerView.getLayoutManager().onRestoreInstanceState(recylerViewState);

This way you can successfully keep your recyclerView's state in a parcelable and restore it whenever you want.

Solution 2:

You cannot get it because it does not really exist. LayoutManager only knows about the views on screen, it does not know the views before, what their size is etc.

The number you can count using the scroll listener is not reliable because if data changes, RecyclerView will do a fresh layout calculation and will not try to re-calculate a real offset (you'll receive an onScroll(0, 0) if views moved).

RecyclerView estimates this value for scrollbars, you can use the same methods from View class.

computeHorizontalScrollExtent

computeHorizontalScrollRange

computeHorizontalScrollOffset

These methods have their vertical counterparts as well.

Solution 3:

I came to the question just wanting to get the item position index that is currently scrolled to. For others who want to do the same, you can use the following:

LinearLayoutManager myLayoutManager = myRecyclerView.getLayoutManager();
int scrollPosition = myLayoutManager.findFirstVisibleItemPosition();

You can also get these other positions:

  • findLastVisibleItemPosition()
  • findFirstCompletelyVisibleItemPosition()
  • findLastCompletelyVisibleItemPosition()

Thanks to this answer for help with this. It also shows how to save and restore the scroll position.

Solution 4:

recyclerView.computeVerticalScrollOffset() does the trick.