Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how not to destroy fragment with androidX

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?

like image 932
candrwow Avatar asked Jul 25 '18 06:07

candrwow


1 Answers

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)

like image 100
Zika Avatar answered Nov 01 '22 03:11

Zika