android - 如何在启用安全参数的不同导航图中重用 fragment ?

标签 android android-fragments android-architecture-components android-architecture-navigation android-safe-args

我正在尝试在启用了安全参数的不同导航图中重用一个 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/

相关文章:

android - 什么会导致应用程序在通过 USB 安装时运行,但在从 Play 商店安装时却不能运行

java - 使用新 fragment 动态更新 ViewPager

android - 从 LiveData 触发第二个查询并合并结果(Firestore)?

android - 我可以在我的 View 模型中创建实时数据观察器吗?还是我应该始终观察 fragment/Activity ?

android - 如何将 ViewModel 与 Repository 连接,以便将数据传播到 View(MVVM、Livedata)

android - 在 android 中更改现有 db4o 中的类属性

android - 如何获取设备的传输(Tx)功率值?

android - 使用 Geocoder (Android) 绘制路径有什么限制吗?

android - fragment 翻转和丢失图像

android - 重用 Fragment 或布局文件