now ,I try androidX's navigation and bottom-navigationbar,when I use it like below
supportFragmentManager = getSupportFragmentManager();
navHostFragment =(NavHostFragment)supportFragmentManager.findFragmentById(R.id.frag_nav);
navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(navigation, navController);
I found an issue,everytime switch the bottomNavigationBar,the fragment will be recreate,all network task in target fragment will be redo,how to keep fragment's state when it switch in androidX?
I also had the same issue. I'm using BottomNavigationView with navigation architecture components and every time fragment is recreated. This is intended behaviour as you can see in Google issue tracker (https://issuetracker.google.com/issues/109856764).
So the right way to approach this is to save current view state in ViewModel and observe that state in every newly created fragment. You need to do all your network tasks in ViewModel.
Also take care of the way you fetch ViewModel inside fragment. If you do it like this viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
, ViewModel will get fragment scope(it will be destroyed when fragment gets destroyed). You have to get ViewModel with activity scope so it can survive switch between fragments. You can do it like this viewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(MyViewModel::class.java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With