安卓:是否可以拥有多个 nav_graph 文件?

5

我使用了Jetpack navigation,但是碎片的数量不断增加。

如文档所述,我们可以将不同的碎片分为不同的导航图。

jetpack nav graph文档

然后我尝试将不同的导航图放在不同的文件中,因为这样更有组织性和可读性。但是当我尝试导航到不同的nav_graph文件时,我遇到了以下错误。

nav_graph_start.xml

<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/nav_graph_start"
    app:startDestination="@id/splashScreen"
    tools:ignore="UnusedNavigation">

    <fragment
        android:id="@+id/splashScreen"
        android:name="com.timetoface.android.splash.SplashFragment"
        android:label="Login Fragment"
        tools:layout="@layout/fragment_splash">

        <action
            android:id="@+id/action_splash_to_login"
            app:destination="@id/nav_graph_auth"
            />
        <action
            android:id="@+id/action_splash_to_home"
            app:destination="@id/nav_graph_home"
            />
    </fragment>
</navigation>

nav_graph_auth.xml

<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/nav_graph_auth"
    app:startDestination="@id/emailLoginScreen"
    tools:ignore="UnusedNavigation">
................................
</navigation>

nav_graph_home.xml

<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/nav_graph_home"
    app:startDestination="@id/emailLoginScreen"
    tools:ignore="UnusedNavigation">
................................
</navigation>

导航目标com.app.android:id/nav_graph_home在从动作com.app.android:id/action_splash_to_home引用时,对于此NavController是未知的。

所以,

多个导航图文件还不支持吗?

我是否错过了应该更改的东西?

2个回答

12

首先,您可以使用include。请参阅此处

示例:first_graph.xml

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

然后将操作设置为包含图表的ID

 <action
        android:id="@+id/action_fragment_to_second_graph"
        app:destination="@id/second_graph" />

同时,您可以使用扩展来使用多个合并的图表。

请查看此处

实际上,每个活动都应该有自己的导航图。


1
@NarekHayrapetyan,你在那个例子中提到的使用多个合并图表的扩展是指什么? - w3bshark
2
@w3bshark 你可以在这里找到更多详细信息:https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample - Narek Hayrapetyan

1

当然,您可以在应用程序中拥有多个导航图。每个Activity只能有一个导航图。我为不同的Activity添加了两个Nav_Graph。运行良好。这是我的Navigation文件夹的截图。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接