Android Switch Fragment Without Losing Ui State (Kotlin)
February 27, 2019Show and Hide Fragment
Whenever you replace a fragment, the UI state (EditText
's text, RecyclerView
's position, etc.) shall be lost unless you save/restore state by overidding onSaveInstanceState(Bundle outState)
and onActivityCreated(Bundle savedInstanceState)
. For temporary state storage, you can use ViewModel.
Another alternative is to show/hide the fragment, which shall maintain the UI state but it will probably consume more memory.
private fun loadFragment(itemId: Int) {
val tag = itemId.toString()
var fragment = supportFragmentManager.findFragmentByTag(tag) ?: when (itemId) {
R.id.navigation_home -> {
TestFragment.newInstance()
}
R.id.navigation_dashboard -> {
Test2Fragment.newInstance()
}
R.id.navigation_notifications -> {
Test3Fragment.newInstance()
}
else -> {
null
}
}
if (fragment != null) {
val transaction = supportFragmentManager.beginTransaction()
if (viewModel.lastActiveFragmentTag != null) {
val lastFragment = supportFragmentManager.findFragmentByTag(viewModel.lastActiveFragmentTag)
if (lastFragment != null)
transaction.hide(lastFragment)
}
if (!fragment.isAdded) {
transaction.add(R.id.fragmentContainer, fragment, tag)
}
else {
transaction.show(fragment)
}
transaction.commit()
viewModel.lastActiveFragmentTag = tag
}
}
NOTE: ViewModel is required to store lastActiveFragmentTag
, else the state is lost upon configuration change/screen rotation.
NOTE: To show/hide fragment in the Android BottomNavigationView With Fragment (Kotlin) example.
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- 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
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- 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