I hope you're all doing well.
I have a problem about navigation graphs. You can see the structure in the image below;
So we have 2 different navigation graphs;
navigation_A
and navigation_B
.
I need to navigate to Fragment Y
and Fragment Z
from a fragment in nested graph which is navigation_B
.
The problem is;
<include>
for navigation_B
, I can not use it as NavHost
.Fragment Y
or Fragment Z
. I need to use navigation_B
as NavHost
, also i need to be able to navigate to Fragment Y
and Fragment Z
. How can I achieve that?
Thank you!
Your navigation graph structure breaks the recommended navigation pattern!
But for your needs, I have a way to workaround.
Method 1: First, FragmentY and FragmentZ need to have their own deeplink.
<fragment
android:id="@+id/fragY"
android:name=".FragmentY"
tools:layout="@layout/frag_y>
<deepLink
android:id="@+id/"
app:uri="any-app://internal_navigation_frag_y" />
</fragment>
<fragment
android:id="@+id/fragZ"
android:name=".FragmentZ"
tools:layout="@layout/frag_z>
<deepLink
android:id="@+id/dlink_frag_z"
app:uri="any-app://internal_navigation_frag_z" />
</fragment>
Then, Inside a Fragment that lives in navigation_b. Let's call it FragmentB
// navigate to FramgmentY
val deeplinkY = Uri.parse("any-app://internal_navigation_frag_y")
findNavController().navigate(deeplinkY)
// navigate to FramgmentZ
val deeplinkZ = Uri.parse("any-app://internal_navigation_frag_z")
findNavController().navigate(deeplinkZ)
You can store the string any-app://internal_navigation_frag_y
and any-app://internal_navigation_frag_z
in string.xml file though.
Check this out: https://developer.android.com/guide/navigation/navigation-navigate#uri
Method 2: Inside the nested graph navigation_B, define 2 global actions that point to fragmentY and fragmentZ. Since navigation_B is a NavHost, so it will know about FragmentY and FragmnentZ
Check this: https://developer.android.com/guide/navigation/navigation-global-action
When you use nested navigation graph the inner graph should not know anything about the outside graph. In this case graph_B should not know about the existence of a FragmentY or FragmentZ. What you should do is deliver a result from your graph_B to whomever launched it. Then at that point decide whether to go FragmentY or FragmentZ.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.