首页 > 解决方案 > 如何将值传递回导航架构组件中的片段?

问题描述

假设我在片段 A 中有一个类的 obj 并将其传递给片段 B。当单击向上按钮(后退按钮)时,我希望将相同的对象传回。

我可以知道何时单击向上按钮(后退按钮)并了解片段名称。但是发回参数不起作用。它显示学生 val 丢失并且没有 defaultValue。当我给出默认值时,它会给出错误,为 public open fun fragmentBTofragnentA 提供的参数过多

这是下面的代码。

覆盖乐趣 onSupportNavigateUp(): Boolean {

val navController = this.findNavController(R.id.myNavHostFragment)
Log.d("Up button", "Main activity")

val id = navController.currentDestination!!.id
Log.d("Now id is: ", "${id.toString()}")

val label = navController.currentDestination!!.label
Log.d("Now id is: ", "${label.toString()}")

if (label == "FragmentB") {
    navController.navigate(FragmentBDirections.actionFragmentBToFragmentA(
        obj
    )
    return false
}

return navController.navigateUp()

导航文件

<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="FragmentA">
        <action
            android:id="@+id/action_fragmentA_to_fragnentB"
            app:destination="@+id/fragmentB" />
        <argument android:name="student"
            app:argType="com.example.StudentWork.Student" />
    </fragment>

    <fragment
        android:id="@+id/fragmentB"
        android:name="com.example.fragmentdatapassings.FragmentB"
        android:label="FragmentB">
        <action
            android:id="@+id/action_fragmentB_to_fragnentA"
            app:destination="@+id/fragmentA" />
        <argument android:name="student"
            app:argType="com.example.StudentWork.Student" />
    </fragment>

任何帮助,将不胜感激。提前致谢。

标签: androidnavigationfragment

解决方案


您可以如下添加默认值和可为空的属性,并检查错误是否已解决。您还可以查看此示例

<argument android:name="student"
          app:argType="com.example.StudentWork.Student" 
          android:defaultValue="@null"
          app:nullable="true" />

推荐阅读