Skip to content

Instantly share code, notes, and snippets.

@JakeSteam
Created January 7, 2019 20:02
Show Gist options
  • Save JakeSteam/ce074069c98deb764b9d74e596b87a69 to your computer and use it in GitHub Desktop.
Save JakeSteam/ce074069c98deb764b9d74e596b87a69 to your computer and use it in GitHub Desktop.
"Saving and restoring a RecyclerView's position in Android" @ https://blog.jakelee.co.uk/saving-and-restoring-a-recyclerviews-position-in-android
interface ListPositioner {
val recyclerScrollKey: String
fun loadListPosition()
fun saveListPosition()
fun resetListPosition()
}
override val recyclerScrollKey = "uk.co.jakelee.scrollposition"
override fun saveListPosition() {
val position = (myRecycler.layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition()
PreferenceManager.getDefaultSharedPreferences(activity!!)
.edit()
.putInt(recyclerScrollKey, position)
.apply()
}
override fun loadListPosition() {
var scrollPosition = PreferenceManager.getDefaultSharedPreferences(activity!!).getInt(recyclerScrollKey, 0)
if (scrollPosition > 0 && scrollPosition < myRecycler.layoutManager.childCount) {
scrollPosition++ // To offset the "completely visible" item under the action bar
}
myRecycler.scrollToPosition(scrollPosition)
}
override fun resetSavedListPosition(){
PreferenceManager.getDefaultSharedPreferences(activity!!)
.edit()
.putInt(recyclerScrollKey, 0)
.apply()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment