Search code examples
javaandroidandroid-fragmentsuinavigationcontroller

Fragments overlapping in Navigation Drawer Activity project when trying to display a fragment that isn't in the menu


I created a simple project using the "Navigation Drawer Activity" template.
When I try to navigate to a fragment that isn't in the navigation menu the fragment appears on top of the current fragment. enter image description here
I am using this in order to navigate to the fragment that isn't in the navigation menu I use this:

FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction().replace(R.id.nav_host_fragment, nextFrag).commit();

All the app_bar_main and content_main xml files are exactly the same as have been generated by android studio.

I use "nav_host_fragment" above because in my content_main file I have:

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

I tried wrapping another container around it and using that, but nothing changed.


Solution

  • You should never be using a FragmentTransaction when using a NavHostFragment and the Navigation Component (in fact, even when you aren't using those, you cannot ever replace a <fragment> added fragment.

    Instead, you should follow the Tie destinations to menu items and add your fragment to your res/navigation/mobile_navigation.xml file and make sure that the ID of your menu.xml file item matches the android:id of the destination in your graph.