Load fragment into navigation programmatically

Viewed 1468

I created a new project from the Navigation Drawer Activity Template in android studio and I have the following XMLs.

content_main.xml

<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_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<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/nav_shopping_list">

    <fragment
        android:id="@+id/nav_products_list"
        android:name="com.example.producttracker.ui.products_list.ProductsListFragment"
        android:label="@string/menu_products_list"
        tools:layout="@layout/fragment_products_list" />

</navigation>

The problem is that when I have a button in my product_list fragment which when clicked should load a new fragment replacing the current one. However, at the moment it just loads a new fragment on top of the existing one.

code used for loading the new fragment:

                AppCompatActivity activity = (AppCompatActivity) view.getContext();

                Fragment inputFragment = new ProductInputFragment();


                FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.nav_host_fragment, inputFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();

From my understanding, the reason is that the product_list fragment is not added programmatically so it cannot be replaced by the FragmentManager. If this is the case, how do I load that fragment programmatically? I read hundreds of articles but I am still confused because in my case there is a navigation thing involved.

2 Answers

I have a hacky solution for you :

Add a container in your layout, hide and unhide fragment and container based on your requirement.

Related