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

fer*_*spr 6 android android-fragments android-architecture-components android-architecture-navigation android-safe-args

我正在尝试在启用安全参数的不同导航图中重用片段。我注意到如果操作不同,我会收到编译错误。这是因为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>
  ...
Run Code Online (Sandbox Code Playgroud)

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>
  ...
Run Code Online (Sandbox Code Playgroud)

一个简单的用例:一个有两个流程的银行应用程序:取款和存款,因此你可以有两个导航图。你可以有一个AmountFragment你可以只输入一个数字的地方,这可以重复用于提款或存款。但是,根据流程的不同,操作/目的地可能会有所不同。

那么,如何重用这个片段呢?

dab*_*248 8

在边缘情况下,使用带有bundle的navigate()而不是actions。不调用\xe2\x80\x99t

\n\n
findNavController().navigate(FragmentDirections.goToDetailFragment(id))\n
Run Code Online (Sandbox Code Playgroud)\n\n

但改为使用

\n\n
findNavController().navigate(R.id.DetailFragment, bundleOf("id" to 5))\n
Run Code Online (Sandbox Code Playgroud)\n\n

这样,您就不会\xe2\x80\x99 依赖生成的方向,但仍然可以使用 DetailFragment 的 Navigation 和 SafeArgs 功能。

\n\n

https://code.allaboutapps.at/articles/android-jetpack-navigation-pitfalls/#reuse-fragments-in-multiple-navigation-graphs

\n