Skip to content

Instantly share code, notes, and snippets.

@eoinfogarty
Created July 21, 2017 07:11
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 eoinfogarty/49de283f66ca072996e03822617a9241 to your computer and use it in GitHub Desktop.
Save eoinfogarty/49de283f66ca072996e03822617a9241 to your computer and use it in GitHub Desktop.
Kotlin extension methods to simplify saving and restoring a recyclerviews scroll postion
import android.os.Bundle
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
/**
* We have to handle restoring a recyclerviews scroll position oneself.
* Add a extension field so we don't have to handle the key ourselves anymore
* Add a post to avoid some bug where recyclerview does not restore scroll position
*
* override fun onSaveInstanceState(outState: Bundle) {
* super.onSaveInstanceState(outState)
* viewModel.saveState(outState)
* binding.recycler.saveLayoutManagerState(outState)
* }
*
* override fun onRestoreInstanceState(savedState: Bundle) {
* super.onRestoreInstanceState(savedState)
* binding.recycler.postRestoreLayoutManagerState(savedState)
* }
*/
val RecyclerView.KEY_RECYCLER_VIEW_STATE: String
get() = "recycler_view_state"
fun RecyclerView.saveLayoutManagerState(outState: Bundle) {
val layoutState = this.layoutManager.onSaveInstanceState()
outState.putParcelable(this.KEY_RECYCLER_VIEW_STATE, layoutState)
}
fun RecyclerView.postRestoreLayoutManagerState(savedState: Bundle?) {
val layoutState = savedState?.getParcelable<Parcelable>(this.KEY_RECYCLER_VIEW_STATE)
this.post { layoutManager.onRestoreInstanceState(layoutState) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment