First Approach:
- In
Included Graph
inside of the <fragment>
block of IncludedFragment
add the destination to the @id/included_fragment
(itself):
<action
android:id="@+id/open_included_fragment"
app:destination="@+id/included_fragment"/>
- In the
Main Graph
make sure that your desired <action>
id is the same as the id of the <action>
in Included Graph
.
Overall your code should be like this:
Main Graph
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_graph"
app:startDestination="@+id/main_fragment">
<include app:graph="@navigation/included_graph"/>
<fragment
android:id="@+id/main_fragment"
android:name="com......MainFragment">
<action
android:id="@+id/open_included_fragment"
app:destination="@+id/included_graph"/>
</fragment>
</navigation>
Included Graph
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/included_graph"
app:startDestination="@+id/included_fragment">
<fragment
android:id="@+id/included_fragment"
android:name="com......IncludedFragment">
<action
android:id="@+id/open_included_fragment"
app:destination="+@id/included_fragment"/>
<argument
android:name="some_argument"
app:argType="integer" />
</fragment>
</navigation>
Then, to navigate to the IncludedFragment
, you should use IncludedFragmentDirections
class:
findNavController().navigate(
IncludedFragmentDirections.openIncludedFragment(69)
)
Second Approach:
- Use the same
Main Graph
navigation graph XML
as in the First Approach.
Included Graph
should be like this:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/included_graph"
app:startDestination="@+id/included_fragment">
<fragment
android:id="@+id/included_fragment"
android:name="com......IncludedFragment">
<argument
android:name="some_argument"
app:argType="integer" />
</fragment>
</navigation>
- Create an extended
NavDirections
class to allow the passing of the arguments (because the default generated one is ActionOnlyNavDirections
without arguments):
class ActionArgumentsNavDirections(
override val actionId: Int,
override val arguments: Bundle
) : NavDirections
- Use
ActionArgumentsNavDirections
in the navigation method, where actionId
equals to R.id.open_included_fragment
, and arguments
should be initialized with the help of IncludedFragmentArgs
class, like this:
findNavController().navigate(
ActionArgumentsNavDirections(
actionId = R.id.open_included_fragment,
arguments = IncludedFragmentArgs(69).toBundle()
)
)