将参数传递给嵌套的导航体系结构组件图

Alg*_*gar 10 android android-architecture-components android-architecture-navigation

如何将参数传递给嵌套的Navigation体系结构组件图?

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

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

那我该怎么办?

Alg*_*gar 15

全局动作可能是一种方式,但是一旦将嵌套图提取到自己的图中,我并没有得到想要的效果.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>
Run Code Online (Sandbox Code Playgroud)

要将参数传递给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>
Run Code Online (Sandbox Code Playgroud)

换句话说,只需将与期望<argument ... />root_graph操作中添加的操作相同的操作添加到操作中即可nested_graph

  • 同意这似乎是目前唯一的解决方法。有一个改进此功能的功能请求:https://issuetracker.google.com/issues/109505019 (4认同)