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)

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.