'How to use BottomNavigationView and Jetpack Navigation with Fragments and do not destroy fragment view's
In my app's main activity, I have BottomNavigationView with four items/tabs. Each tab has its own fragment. I use Jetpack Navigation components to navigate between these fragments.
When I navigate to another fragment using NavController.navigate(...), previous fragment view is being destroyed. One of my fragment contains map view, this makes fragment view creation heavy operation. When user changes BottomNavigationView tab, there is noticeable delay on older android phones when navigating to fragment with map view. Can I modify NavController not to destroy view, instead hide and show the view?
TLDR: How to change Jetpack Navigation not to destroy fragment's view. Instead, just hide & show view?
There is already some discussion in this topic, but as Jetpack Navigation lib has evolved a lot, most of the solutions are outdated. Jetpack Navigation 2.4.0 brings support for multiple backstack etc but as far as I understand, no official solution to keep fragment view alive?
Solution 1:[1]
I have same problem, still can't find solution in Navigation document or sample.
For now I use old way, use supportFragmentManager to add and addToBackStack, so I can keep previous fragment not destroy. Just a workaround way, hope someone can provide a better solution.
My sample code as below:
val fragment = CreateGroupWebFragment()
activity?.supportFragmentManager?.beginTransaction()
?.add(R.id.main_tab_nav_host_fragment, fragment, fragment.TAG)
?.addToBackStack(fragment.TAG)
?.commit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faydee |
