Method 1 :
@onPause
long currentVisiblePosition = 0; // this variable should be static in class currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
@onResume
((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(currentVisiblePosition); currentVisiblePosition = 0;
Method 2 :
protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); // Save list state mListState = mLayoutManager.onSaveInstanceState(); state.putParcelable(LIST_STATE_KEY, mListState); }
protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); // Retrieve list state and list/item positions if(state != null) mListState = state.getParcelable(LIST_STATE_KEY); }
if we are in fragment onRestoreInstanceState is not available so we can use this :
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Retrieve list state and list/item positions if(state != null) mListState = state.getParcelable(LIST_STATE_KEY); } }
Then update the LayoutManager (for example in onResume() or after loading recyclerView):
@Override protected void onResume() { super.onResume(); if (mListState != null) { mLayoutManager.onRestoreInstanceState(mListState); } }
References
https://stackoverflow.com/questions/36568168/how-to-save-scroll-position-of-recyclerview-in-android
https://stackoverflow.com/questions/27816217/how-to-save-recyclerviews-scroll-position-using-recyclerview-state
https://stackoverflow.com/questions/43857824/kotlin-static-methods-and-variables
https://stackoverflow.com/questions/28236390/recyclerview-store-restore-state-between-activities