Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
–
–
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"
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
–
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.