我正在尝试在启用了安全参数的不同导航图中重用一个 fragment 。我注意到如果操作不同,我会收到编译错误。这是因为 xxxFragmentDirections
自动生成的代码只会生成其中一个 Action 。
在 nav_graph_1.xml :
<navigation
...
<fragment
android:id="@+id/myFragment"
android:name="com.example.android.MyFragment">
<action
android:id="@+id/next_action"
app:destination="@+id/dest_one" />
</fragment>
...
在 nav_graph_2.xml :
<navigation
...
<fragment
android:id="@+id/myFragment"
android:name="com.example.android.MyFragment">
<action
android:id="@+id/other_action"
app:destination="@+id/other_dest" />
</fragment>
...
一个简单的用例:一个银行应用程序有两个流程:提款和存款,因此您可以有两个导航图。你可以有一个
AmountFragment
您可以在其中输入一个数字,然后可以将其重复用于提款或存款。但是,根据流程,操作/目的地可能会有所不同。那么,如何重用这个 fragment 呢?
最佳答案
将 navigate() 与 bundle 一起使用,而不是在极端情况下使用操作。不要打电话
findNavController().navigate(FragmentDirections.goToDetailFragment(id))
而是使用
findNavController().navigate(R.id.DetailFragment, bundleOf("id" to 5))
这样您就不必依赖生成的方向,但仍然可以使用 DetailFragment 的 Navigation 和 SafeArgs 功能。
https://code.allaboutapps.at/articles/android-jetpack-navigation-pitfalls/#reuse-fragments-in-multiple-navigation-graphs
关于android - 如何在启用安全参数的不同导航图中重用 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704805/