Member-only story
Saving Fragment States with BottomNavigationView

The BottomNavigationView
is the latest design trend for Android development, as seen in several example apps below.

Each of the tabs could have a stack of fragments shown, and user could swap between them.

With this, we hope when we tap across the bottom navigation, the Fragments will be reloaded accordingly. However, if we do a simple fragment transaction, look at the result below.

When we switched tabs and came back, the entire fragment is gone. It didn’t restore to its previous state. So how to solve the problem?
Solution
Saving Fragment State
The trick to it, is having the ability to save Fragment state when we switch the tab.
Android does gave us ability to get the SavedState using saveFragmentInstanceState
function as below.
val savedState = supportFragmentManager.saveFragmentInstanceState(fragment)
And to restore, it is as below
fragment.setInitialSavedState(savedState)
Handling Multiple Tabs
The above is cool. However, we have three tabs here (or possibly more), and we want a scalable way to save & restore the Fragment state.
We could quickly think of HashMap
of tab.id
and Fragment.SavedState
. However this is not ideal, as we also want to store the HashMap
in the Bundle
later for state restoration (in case the app us killed by the system).
A better solution is to use SparseArray
instead. In our case would be SparseArray<Fragment.SavedState>
. The reason is, Android provides us an API to save SparseArray
in a Parcelable
way.
outState?.putSparseParcel…