Search code examples
javaandroidreplacefragmentnavigation-drawer

Replace fragment by another using default navigation drawer activity template


I have a navigation drawer using fragments created from the default "Navigation Drawer Activity" template in Android Studio. Inside a fragment A, I want to open another fragment B. So the fragment B must replace fragment A. I saw on google, that I should use FrameLayout to Dynamically change the current displayed fragment.

    <FrameLayout
        android:id="@+id/nav_host_frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <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" />
    </FrameLayout>

To change fragment, I am using the code below, when I am clicking on a button in the fragment that I want to be replaced

NewCalendarEvent newEventFrag = new NewCalendarEvent();
getActivity().getSupportFragmentManager().beginTransaction()
             .replace(R.id.nav_host_frame_layout, newEventFrag)
             .addToBackStack(null)
             .commit();

Currently, when I click on the button, the two fragments are show. Is because I am using fragment and frameLayout together ? What I am doing wrong ?


Solution

  • If you are using a NavHostFragment and the Navigation Component, then you never use a FragmentTransaction. Instead you navigate to a screen by using the APIs on NavController.