Created
July 21, 2017 07:11
-
-
Save eoinfogarty/49de283f66ca072996e03822617a9241 to your computer and use it in GitHub Desktop.
Kotlin extension methods to simplify saving and restoring a recyclerviews scroll postion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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