关于NavigationAdvancedSample中底部导航Fragment不被detached及EditText数据留存的技术咨询
Hey there! Let's break down your questions about the NavigationAdvancedSample step by step:
How to implement this in your own code
By default, the Navigation component replaces fragments when switching bottom navigation destinations, which detaches the previous fragment from the FragmentManager. To prevent this (so fragments are just hidden instead of detached), you'll need to override the default fragment navigation behavior to use hide()/show() instead of replace().
How NavigationAdvancedSample achieves this
The sample uses a custom FragmentNavigator implementation called KeepStateNavigator to handle this logic. Here's where the magic happens:
Custom Navigator Setup: In
MainActivity, they create this custom navigator and add it to theNavController's navigator provider:val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navigator = KeepStateNavigator(this, navHostFragment.childFragmentManager, R.id.nav_host_fragment) navHostFragment.navController.navigatorProvider.addNavigator(navigator)Override Navigation Logic: The
KeepStateNavigatoroverrides thenavigate()method. Instead of replacing the current fragment, it:- Hides the currently displayed fragment
- If the target fragment already exists in the FragmentManager, it shows it
- If not, it adds the new fragment to the container
This way, the Home (Title) Fragment is never detached—just hidden—when switching to Leaderboard or Register. That's why it stays in memory instead of being detached like in your own code.
Great question! Even though the Register Fragment gets detached, its data doesn't disappear because of how Android handles fragment and view state:
- Detach vs. Destroy: When a fragment is detached, its instance stays alive in memory—only its view hierarchy is destroyed. This is different from fragment destruction, where the entire instance is wiped.
- Automatic View State Saving: Android automatically saves the state of views like
EditTextwhen the fragment'sonDestroyView()is called. This state is stored in the fragment'sSavedStateRegistry. - State Restoration: When the Register Fragment is reattached and
onCreateView()is called again, the system restores the saved view state to the newly created view hierarchy. This includes the text you typed into the EditText—no ViewModel required!
This behavior is enabled by default, as long as you don't disable view state saving (e.g., by calling setSaveEnabled(false) on the EditText or fragment).
内容的提问来源于stack exchange,提问作者Isaac Lee

