在导航图中多次使用相同的片段

sne*_*yan 6 android android-architecture-navigation

我想迁移我的项目以使用导航组件。在我的 Activity 中有一个底部导航,它可以浏览同一 Fragment 的不同实例(使用不同的参数)。

这里解释了bottomNavigation支持。但是是否可以在同一个导航图中使用不同的 ID 和参数重用同一个 Fragment?

我在谷歌文档中找不到方法。

小智 3

您应该能够定义具有多个目的地的 nav_graph 并重用相同的片段。像这样的事情,

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/mobile_navigation"
  app:startDestination="@+id/navigation_tab1">

  <fragment
      android:id="@+id/navigation_tab1"
      android:name="com.myapp.MyFragment"
      android:label="Tab1">

      <action
          android:id="@+id/action_goto_page1"
          app:destination="@id/navigation_page1" />
      <argument
          android:name="tab1_arg1"
          android:defaultValue="Default"
          app:argType="string" />
  </fragment>

  <fragment
      android:id="@+id/navigation_tab2"
      android:name="com.myapp.MyFragment"
      android:label="Tab2">

      <action
          android:id="@+id/action_goto_page2"
          app:destination="@id/navigation_page2" />
      <argument
          android:name="tab2_arg1"
          android:defaultValue="Default"
          app:argType="string" />
  </fragment>

  <fragment
      android:id="@+id/navigation_tab3"
      android:name="com.myapp.MyFragment"
      android:label="Tab3">

      <action
          android:id="@+id/action_goto_page3"
          app:destination="@id/navigation_page3" />
      <argument
          android:name="tab3_arg1"
          android:defaultValue="Default"
          app:argType="string" />
  </fragment>
</navigation>
Run Code Online (Sandbox Code Playgroud)

但是,最好重构代码以拥有多个片段(每个片段做一件事),以便更好地维护和干净的代码。