首页 > 解决方案 > 将参数传递给嵌套的导航架构组件图

问题描述

如何将参数传递给嵌套的导航架构组件图?

假设我构建导航图以从中导航FragmentA --> Nested,其中Nested包含FragmentB --> FragmentC...

如果这是一个纯FragmentA --> FragmentB...图表,我会设置导航FragmentADirections.actionFragmentAToFragmentB(argument = foo)。但是,一旦您B --> C变成Nested... ,该操作就需要零参数

那我该怎么办?

标签: androidandroid-architecture-componentsandroid-architecture-navigation

解决方案


全局操作可能是一种方式,但是一旦我将嵌套图提取到它自己的.xml. 但事实证明这是令人尴尬的简单 - 只需在代码中手动添加参数到您的操作中。

与该问题相关的示例是:

将嵌套图保存到nested_graph.xml,它看起来像

<navigation
    android:id="@+id/nested_graph"
    app:startDestination="@id/fragmentB"
    ...>

    <fragment 
        android:id="@+id/fragmentB"
        ...>
        <argument
            android:name="foo"
            app:argType="integer"/>
        <action 
            ... // navigation action to FragmentC />
    </fragment>

    <fragment ...  // FragmentC stuff
</navigation>

nested_graph.xml要从不同的图表传递参数,说root_graph.xml

<navigation
    android:id="@+id/root_graph"
    app:startDestination="@id/fragmentA"
    ...>

    <fragment 
        android:id="@+id/fragmentA"
        ... >
        <action
            android:id="@+id/action_fragmentA_to_nested_graph"
            app:destination="@id/nested_graph">
            <argument
                android:name="foo"
                app:argType="integer"/>
        </action>
    </fragment>
    <include app:graph="@navigation/nested_graph"/>
</navigation>

换句话说,只需将与<argument ... />root_graph期望在nested_graph.


推荐阅读