ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Member-only story

Saving Fragment States with BottomNavigationView

Elye - A One Eye Dev By His Grace
ProAndroidDev
Published in
3 min readDec 20, 2018

--

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (6)

Write a response