Search code examples
androidandroid-fragmentsnavigationandroid-jetpack-navigation

How to add fragment on top of another fragment using navigation jetpack?


I want to add a fragment on top of another fragment. But while using navigation jetpack, it seems like replacing the fragment not adding.

I actually want to display a pop-up page so both fragments could communicate with each other, which seems to work for old add fragment function, but recently our project has been replaced with navigation jetpack.


Solution

  • One of the options would be to make your second fragment extend DialogFragment and add it to your navigation graph as a <dialog> and not a <fragment>. It will be automatically shown as a dialogue by navigation component.

    Here is an example:

        <dialog
            android:id="@+id/myPopupDialogFragment"
            android:name="project.package.name.MyDialogFragment"
            android:label="MyDialogFragment">
            <!-- add arguments if you wish -->
        </dialog>
    

    You can make this dialogue to be presented fullscreen using a fullscreen theme or as bottom sheet using:

    Theme.MaterialComponents.Light.BottomSheetDialog