Android Save and Restore RecyclerView State/Position
May 5, 2020Fragment
class BatchFragment : Fragment() {
private val viewModel: BatchViewModel by viewModels()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initList()
}
override fun onDestroyView() {
super.onDestroyView()
viewModel.listState = list.layoutManager?.onSaveInstanceState()
// val layoutManager = list.layoutManager as GridLayoutManager
// val position = layoutManager.findFirstVisibleItemPosition()
}
override fun initList() {
adapter = LocalAdapter(viewModel)
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (viewModel.listState != null) {
list.layoutManager?.onRestoreInstanceState(viewModel.listState)
// val layoutManager = list.layoutManager as GridLayoutManager
// layoutManager.scrollToPositionWithOffset(position, 0)
}
}
})
list.adapter = adapter
// load items into adapter
// adapter.submitList(...)
}
private class LocalAdapter(val viewModel: BatchViewModel) : ListAdapter<ViewItem, LocalAdapter.ViewHolder>(DiffCallback()) {
// ...
}
}
NOTE: I am using Jetpack Navigation, so I listen to onDestroyView
to save state (when navigate to another fragment).
ViewModel
class BatchViewModel(application: Application) : AndroidViewModel(application) {
var listState: Parcelable? = null
}
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- coroutines
- crashlytics
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetson-nano
- kotlin
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn