- Create the extension function for the NavController, or, in java, you could create a static helper class with method perhaps.
fun NavController.navigate(directions:NavDirections, @NavigationRes graphId : Int) {
val currentGraph = graph
val desiredAction = currentGraph.getAction(directions.actionId)
val destId = if(desiredAction == null) {
val graph = navInflater.inflate(graphId)
currentGraph.addAll(graph)
graph.getAction(directions.actionId)!!.destinationId
} else {
desiredAction.destinationId
}
navigate(destId, directions.arguments)
}
- Have a main navigation graph:
navigation_main.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation_main"
app:startDestination="@id/fragment">
<fragment
android:id="@+id/fragment"
android:name="my.package.MyFragment"/>
</navigation>
- Create a library navigation graph (in your library):
navigation_library.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation_library"
app:startDestination="@id/another_fragment">
<fragment
android:id="@+id/another_fragment"
android:name="my.package.AnotherFragment">
<argument
android:name="defaultValue"
android:defaultValue="@null"
app:argType="java.time.LocalDate"
app:nullable="true" />
</fragment>
<action
android:id="@+id/action_global_another_fragment"
app:destination="@id/another_fragment" />
</navigation>
- Add this code inside e.g. a button click listener in MyFragment
val directions = AnotherFragmentDirections.actionGlobalAnotherFragment(LocalDate.now())
parent.findNavController().navigate(directions, R.navigation.navigation_library)
If you need to navigate to another library from this library, you'd simply create a graph in that library and navigate to the destination inside it using the same trick.
I have this situation since I have a navigation graph in my app. The app depends on a feature module, and that feature module makes use of what I'd call a core module of useful fragments to pick date and time.