Skip to content

Instantly share code, notes, and snippets.

@jaiselrahman
Last active March 6, 2020 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaiselrahman/b66161d555dd366a6a4d7d657ef3fe60 to your computer and use it in GitHub Desktop.
Save jaiselrahman/b66161d555dd366a6a4d7d657ef3fe60 to your computer and use it in GitHub Desktop.
//Saving scroll state
val position = linearLayoutManager.findFirstVisibleItemPosition()
val offset = linearLayoutManager.getChildAt(0).let {
if (it == null) 0 else it.top - linearLayoutManager.paddingTop
}
postFeedViewModel.scrollState = ScrollState.of(position, offset)
//Restoring scroll state
val scrollState = postFeedViewModel.scrollState
linearLayoutManager.scrollToPositionWithOffset(scrollState.position, scrollState.offset)
//ViewModel
class PostFeedViewModel() : ViewModel {
...
var scrollState: ScrollState
get() = ScrollState.of(
Preference.get(KEY_POST_SCROLL_POSITION, 0),
Preference.get(KEY_POST_SCROLL_OFFSET, 0)
)
set(scrollState) {
Preference.put(KEY_POST_SCROLL_POSITION, scrollState.position)
Preference.put(KEY_POST_SCROLL_OFFSET, scrollState.offset)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment