Search code examples
androidandroid-fragmentsandroid-architecture-navigationandroid-jetpack-navigation

how to open multiple instances of a fragment in navigation component?


I working on a social media App. when user click on a post, a new fragment open and some related post showing under it. if user click on a related post, new instance of that fragment must open and show clicked post and related posts under it. this page also have this behavior. each page must add to back stack.

for using navigation component, in this case destination fragment is current fragment with different argument. can do this in navigation component?


Solution

  • we can open multiple instances of a fragment by using deeplink in navigation.xml :

    <fragment
          android:id="@+id/navigation_profile"
          tools:layout="@layout/fragment_profile_owner"
          android:label="@string/profile" >
    
        <deepLink
            android:id="@+id/profileDeepLink"
            app:uri="myapp://?user_id={user_id}" />
    
      </fragment>
    

    and then you can open new fragment by:

    findNavController().navigate(Uri.parse("myapp://?user_id=${id}"))
    

    and you can get argument in destination fragment by:

    arguments?.getString("user_id")
    

    and put this in activity tag in manifest (if you want to open this page out of app):

    <activity
        android:name=".ui.activity.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
    
        <nav-graph android:value="@navigation/navigation" />
    
    </activity>