How to save scroll position of RecyclerView in Android?

后端 未结 8 1384
耶瑟儿~
耶瑟儿~ 2020-11-27 06:20

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 cho

8条回答
  •  迷失自我
    2020-11-27 07:04

    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;
    

提交回复
热议问题