Skip to content

Instantly share code, notes, and snippets.

@SurajBahadur
Created July 1, 2022 09:29
Show Gist options
  • Save SurajBahadur/d7749884bdd5172b2e91fe6a96c34f41 to your computer and use it in GitHub Desktop.
Save SurajBahadur/d7749884bdd5172b2e91fe6a96c34f41 to your computer and use it in GitHub Desktop.
Scroll to previous saved position in recyclerview
//Create a variable in shared viewmodel to hold the state
var listState: Parcelable? = null
//onDestroyView() in case of fragment, saved the state of layout manager attached to rv
bookMarkViewModel.listState = binding.recyclerViewMain.layoutManager?.onSaveInstanceState()
//Suppose you have move from SCREEN A to SCREEN B and on SCREEN A, you have save the state in the listState variable and when
//you come back to SCREEN A then you need to restore the layoutManager state as below
if(listState!=null){
binding.recyclerViewMain.layoutManager?.onRestoreInstanceState(bookMarkViewModel.listState);
}
//Note: For the first time you have to add the null check for listState.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment