从另一个图形导航到片段而不是起始目的地

Navigate to a fragment from another graph without it being the start destination

在我的第一张图中,我有以下内容:

<?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/firstGraph"
    app:startDestination="@id/listFragment">

    <fragment
        android:id="@+id/listFragment"
        android:name="com.example.ListFragment">

        <action
            android:id="@+id/action_list_to_details"
            app:destination="@id/detailsFragment" />

    </fragment>

    <fragment
        android:id="@+id/detailsFragment"
        android:name="com.example.DetailsFragment">

    </fragment>
</navigation>

在我的第二张图中,我有以下内容:

<?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/secondGraph"
    app:startDestination="@id/dashboardFragment">

    <include app:graph="@navigation/firstGraph" />

    <fragment
        android:id="@+id/dashboardFragment"
        android:name="com.example.DashboardFragment">
        <action
            android:id="@+id/action_dashboard_to_notification"
            app:destination="@id/notificationFragment"/>
    </fragment>

    <fragment
        android:id="@+id/notificationFragment"
        android:name="com.example.NotificationsFragment">

        <action
            android:id="@+id/action_notification_to_details"
            app:destination="@id/firstGraph"/>

    </fragment>
</navigation>

我想直接从 "notificationFragment" 导航到 "detailsFragment" 而不是开始目的地,包括第二个图形堆栈

根据 nested graph documentation:

[Nested graphs] also provide a level of encapsulation — destinations outside of the nested graph do not have direct access to any of the destinations within the nested graph.

有一个例外,当您 navigating using a URI 时,有效深度链接到 任何 目的地:

Unlike navigation using action or destination IDs, you can navigate to any URI in your graph, regardless of whether the destination is visible. You can navigate to a destination on the current graph or a destination on a completely different graph.

因此你可以add an implicit deep link to your graph:

<fragment
    android:id="@+id/detailsFragment"
    android:name="com.example.DetailsFragment">
    <deepLink app:uri="android-app://your.package.name/details" />
</fragment>

然后通过 URI 导航到该目的地:

val uri = Uri.parse("android-app://your.package.name/details")
navController.navigate(uri)

只要 <deepLink> 和您传递给 navigate 的内容匹配,您的 URI 是什么并不重要。您拥有的任何参数都需要在 URL.

中进行编码