Created
January 7, 2019 20:02
"Saving and restoring a RecyclerView's position in Android" @ https://blog.jakelee.co.uk/saving-and-restoring-a-recyclerviews-position-in-android
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
interface ListPositioner { | |
val recyclerScrollKey: String | |
fun loadListPosition() | |
fun saveListPosition() | |
fun resetListPosition() | |
} |
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
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