Android导航组件在片段方向之间传递数据

时间:2020-07-06 08:20:56

标签: android kotlin navigation fragment

这是我的导航文件

<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/navigation"
    app:startDestination="@id/fragmentA">

    <fragment
        android:id="@+id/fragmentA"
        android:name="com.example.fragmentdatapassings.FragmentA"
        android:label="Fragment A">
        <action
            android:id="@+id/action_fragmentA_to_fragnentB"
            app:destination="@+id/fragmentB" />
        <argument
        android:name="x"
        app:argType="integer" />
    </fragment>

    <fragment
        android:id="@+id/fragmentB"
        android:name="com.example.fragmentdatapassings.FragmentB"
        android:label="FragmentB">
    </fragment>

</navigation>

这是片段方向数据传递的代码。

val x : Int = 10
val action = FragmentADirections.actionFragmentAToFragnentB(x)
Navigation.findNavController(requireView()).navigate(action)

以上第二行显示错误

太多公开辩论的理由

当我将鼠标悬停在错误上时,它显示添加参数x,我确实单击了它并且确实 在FragmentADirections中添加参数x。但是在再次构建应用程序后,它显示错误 再次。

1 个答案:

答案 0 :(得分:1)

<argument>应该是您要接收的片段,而不是您要发送的片段

如果要将数据从片段 A 传递到 B

  <fragment
        android:id="@+id/fragmentB"
        android:name="com.example.fragmentdatapassings.FragmentB"
        android:label="FragmentB">
        <argument
        android:name="x"
        app:argType="integer" />
    </fragment>

并从片段 A 中删除参数,就可以了

相关问题