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

NavHostFragment vs FragmentContainerView [Android]


Hi there I'm going through the guides for navigation on the developer Android site, and I followed the instructions to create a NavHostFragment:

<fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"

        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

However when that code is there the IDE suggests that I replace the NavHostFragment with FragmentContainerView.

What is the difference and when should they each be used rather than the other?

Thank you


Solution

  • The FragmentContainerView is a customized Layout designed specifically as the container for Fragments. The NavHostFragment is responsible for swapping destinations in the Navigation component.

    You can use:

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/xxxxx"
        app:defaultNavHost="true"
    
        ..>
    

    and:

    val navController = findNavController(R.id.nav_host_fragment)
    

    Or you can use:

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/xxxx"
        app:defaultNavHost="true"
    
        ..>
    

    with:

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController