导航到另一个片段时如何添加参数?

时间:2020-07-20 16:13:46

标签: kotlin android-jetpack-navigation

现在我显示如下对话框片段:

viewModel.onMoreMenuClickEvent.observe(this, Observer { event ->
    event.getContentIfNotHandled()?.let { menuItems ->
        dialogFragment = BottomMenuDialog.newInstance(menuItems = menuItems).also {
            it.setTargetFragment(this, MORE_MENU_REQUEST_CODE)
            activity?.showDialogFragment(it)
        }
    }
})

在我的nav_graph.xml中添加了一个对话框:

<dialog
    android:id="@+id/bottomMenuDialog"
    android:name="com.mandarine.sai.features.menu.BottomMenuDialog"
    android:label="BottomMenuDialog" />

编写导航乐趣:

findNavController().navigate(R.id.bottom_menu_dialog)

但是我如何添加在newInstanceit.setTargetFragment(this, MORE_MENU_REQUEST_CODE)中发送的menuItem?

这也是我的newInstance()的代码:

fun newInstance(
    menuId: String = "",
    menuItems: List<MenuItemData>
): BottomMenuDialog {
    return BottomMenuDialog().apply {
        arguments = Bundle().apply {
            putString(KEY_ID, menuId)
            putSerializable(KEY_ITEMS, ArrayList(menuItems))
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

查看android文档

https://developer.android.com/guide/navigation/navigation-pass-data

定义目标参数

示例:

在您的xml设置参数标签中

enter image description here

当您采取行动时,发送论据

enter image description here

检查ID动作命名

在接收目标的代码中,使用getArguments()方法检索捆绑包并使用其内容。当使用-ktx依赖项时,Kotlin用户还可以使用by navArgs()属性委托来访问参数。

enter image description here