1

I have an app with multiple feature modules that I want to navigate using a single NavHostFragment in my main module.

         app
       |  |  |
feature1  |  feature2
       |  |  |
       common

The nav graph seems to work fine (I can add all the Fragments from the feature modules and the startFragment shows up when I start the app) but sometimes I have to start a navigation from inside the feature modules but I dont have access to the NavHostFragment there.

for example :

findNavController(navHostFragment).navigate(R.id.loginFragment)
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
TeKo
  • 465
  • 1
  • 5
  • 17

1 Answers1

3

As per the findNavController() documentation:

This method will locate the NavController associated with this Fragment, looking first for a NavHostFragment along the given Fragment's parent chain.

This means that you don't need to pass in the NavHostFragment itself, but can pass in any Fragment created by your NavHostFragment and it'll correctly find the NavController.

Therefore in almost all cases, you should be passing this into findNavController():

// From anywhere in one of the Fragments in your navigation graph
findNavController(this).navigate(R.id.loginFragment)
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443