This is a strange one. I have a standard application using tab navigation with one MainActivity
and four Fragment
s that are swapped whenever a user clicks on a bottom tab.
Here’s how the Fragments are swapped:
val appointmentsFragment = AppointmentsFragment()
val chatFragment = ChatFragment()
val journalFragment = JournalFragment()
val profileFragment = ProfileFragment()
lateinit var selectedFragment: Fragment
if (savedInstanceState == null) {
supportFragmentManager.commit {
setReorderingAllowed(true)
add(R.id.fragmentContainer, appointmentsFragment, appointmentsFragment.javaClass.simpleName)
selectedFragment = appointmentsFragment
}
}
bottomNavigation.setOnNavigationItemSelectedListener {
val selection = when(it.itemId) {
R.id.appointments -> appointmentsFragment
R.id.chat -> chatFragment
R.id.journal -> journalFragment
R.id.profile -> profileFragment
else -> { throw IllegalStateException("There are only 4 tabs.") }
}
supportFragmentManager.commit {
setReorderingAllowed(true)
// Detach previous fragment
detach(selectedFragment)
val tag = selection.javaClass.simpleName
if (supportFragmentManager.findFragmentByTag(tag) == null) {
add(R.id.fragmentContainer, selection, tag)
} else {
attach(supportFragmentManager.findFragmentByTag(tag)!!)
}
selectedFragment = selection
}
true
}
Pretty standard stuff. The issue occurs when the following is performed:
- Launch app as normal.
- Background app and switch to settings, and enable or disable “Dark theme” mode.
- Switch back to app, switch tabs if needed
- Observe the corrupted UI
Here are some screenshots showing what occurs after performing those steps (click for larger photo):
As you can see, the UI of the other Fragments is, somehow, still on the screen, even though the Fragments containing those portions of UI were all detached. Additionally, I have confirmed that onDestroyView()
is called for all of those old Fragments, which makes how or why their UI is still visible even more puzzling. It should also be said that when the theme is switched, and the user switches back to the app, the onDestroy
of the MainActivity
is called anyway, which I believe is standard.
Why is this issue occurring, and how can it be fixed? Thank you!