snersesyan
snersesyan

Reputation: 1677

Use same fragment multiple times in navigation graph

I want to migrate my project to use navigation components. In my Activity there is a bottom navigation, which navigates through different instances of the same Fragment (with different arguments).

Here explained about bottomNavigation support. But is it possible to reuse same Fragment in the same navigation graph, with different IDs and params?

I can't find way in google documentations.

Upvotes: 7

Views: 2509

Answers (1)

deepdroid
deepdroid

Reputation: 633

You should be able to define your nav_graph with multiple destinations and reuse the same fragment. Something like this,

<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>

However, it's best to refactor your code to have multiple Fragments (each doing one thing) for better maintenance and clean code.

Upvotes: 3

Related Questions