Search code examples
androidandroid-navigation-graph

Can a second navigation graph be used as a nested navigation graph?


The new android navigation component is what seems to be recommended. Im follow the official tutorial on graph nesting.

To group destinations into a nested graph, do the following:

In the Navigation Editor, press and hold the Shift key, and click on the destinations you want to include in the nested graph. Right-click to open the context menu, and select Move to Nested Graph > New Graph. The destinations are enclosed in a nested graph. Figure 2 shows a nested graph in the Navigation Editor:

Everything works well so far, I just have one issue. The nested graphs are all part of one big xml file, this is an issue because it can lead to merge conflicts when using source control.

So my question is can we have this same functionality if we simply create two navigation graphs and include the new graph as a destination? Will everything work as expected or would there be unintended consequences to doing this. For example poping back to the root of navigation controller? I'm not very familiar with Android but my fear is that a new navigation controller is created and I cannot easily navigate when having two navigation graphs.

Nothing in the tutorial seems to mention this.


Solution

  • As per the Reference other navigation graphs with <include>:

    While this is functionally the same as using a nested graph, include lets you use graphs from other project modules or from library projects

    An <include> is expanded at runtime to function identically to a nested graph - there is no difference in what you can do regarding popping up to other destinations, etc.

    However note that Safe Args does not work across separate navigation graph files (as you could include that graph in multiple other graphs, so there's no guarantee that anything outside of that file actually 'safely' exists), so you would need to confirm that any use of Safe Args is within a single file (using other mechanisms, such as manually navigating or navigating by deep link to navigate to graphs you know exist, but cannot be verified at compile time).