DefaultXYZ DefaultXYZ - 10 months ago 528
Android Question

How to save scroll position of RecyclerView in Android?

I have Recycler view which lays inside of SwipeRefreshLayout. Also, have ability to open each item in another activity.
After returning back to Recycler I need scroll to chosen item, or to previous Y.
How to do that?

Yes, I googled, found articles in StackOverFlow about saving instance of layout manager, like this one: RecyclerView store / restore state between activities.
But, it doesn't help me.


Right now I have this kind of resolving problem, but, of course, it also doesn't work.

private int scrollPosition;

...//onViewCreated - it is fragment
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
data = new ArrayList<>();
adapter.setData(getActivity(), data);

public void onResume() {

public void onPause() {
scrollPosition = recyclerView.getScrollY();

Yes, I have tried scrollTo(int, int) - doen't work.

Now I tried just scroll, for example, to Y = 100, but it doesn't scrolling at all.


Save the current state of recycle view position @onPause:

    positionIndex= llManager.findFirstVisibleItemPosition();
    View startView = rv.getChildAt(0);
    topView = (startView == null) ? 0 : (startView.getTop() - rv.getPaddingTop());

Restore the scroll position @onResume:

    if (positionIndex!= -1) {
        llManager.scrollToPositionWithOffset(positionIndex, topView);

or another way can be @onPause:

long currentVisiblePosition = 0;
currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

restore @onResume:

((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(currentVisiblePosition);
currentVisiblePosition = 0;