如何在启用安全参数的情况下在不同的导航图中重复使用片段?

问题描述 投票:1回答:1

我正在启用安全参数的情况下在不同的导航图中重用片段。我注意到,如果操作不同,则会出现编译错误。这是因为xxxFragmentDirections自动生成的代码将只生成动作之一。

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,您可以在其中输入一个数字,并且可以重复使用该数字来取款或入金。但是,根据流程,操作/目标可能会有所不同。

然后,如何重用此片段?

android android-fragments android-architecture-components android-architecture-navigation android-safe-args
1个回答
0
投票

与bundle一起使用navigation(),而不是在极端情况下使用动作。不要打电话

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

© www.soinside.com 2019 - 2024. All rights reserved.