Reputation: 183
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
Upvotes: 6
Views: 5550
Reputation: 363647
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
Upvotes: 11
Reputation: 1489
If you explore the source code of FragmentContainerView, you will find it extends FrameLayout.
FragmentContainerView includes all features found in Framelayout, with some added features in Fragment Transition and etc..
Note: FragmentContainerView replaces <FrameLayout>
and <fragment>
not NavHostFragment.
To know more about FragmentContainerView, kindly check this article.
I hope this would help.
Upvotes: 2