how can we specify replace or add fragment in Navigation component?
NavHostFragment.findNavController(this).navigate(R.id.action_splashFragment_to_categoriesFragment)
how can we specify replace or add fragment in Navigation component?
NavHostFragment.findNavController(this).navigate(R.id.action_splashFragment_to_categoriesFragment)
If you just use findNavController().navigate(R.id.someDestinationId)
this kind of equals to fragmentManager.add
but if you want the replace behavior and you don't want the user be able to press back and reload the previous activity you should do like this:
findNavController().navigate(R.id.homeFragment, null, NavOptions.Builder()
.setPopUpTo(R.id.loginFragment, true)
.build())
In this case I'm inside LoginFragment and I want to navigate to HomeFragment and I also would like to replace current fragment so the user won't be able to press back and load the LoginFragment again
Jetpack Navigation Component supports replacing fragments as of now.
There is no support for adding fragments.
Workaround to retain api data in fragment when back button is pressed is to either save the data (Fragment viewstate) in a ViewModel and make a check in onViewCreated() or to use Full Screen DialogFragments. For dialog fragment check this https://gist.github.com/utkukutlu/bd2e37253e7184179d923321e3ea72c1