Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 919
snersesyan Avatar asked Sep 10 '19 18:09

snersesyan


People also ask

Can fragments be used in multiple activities?

You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.


1 Answers

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.

like image 80
deepdroid Avatar answered Oct 21 '22 11:10

deepdroid