Another way to simply add a Fragment to FragmentContainerView is by using the attribute android:name=”fragment_class_name_path" in XML. Both the attributes android:name or class are similar things we just need to give the classpath as a value to inflate the fragment.
There is still a bug that will thrown an exception if you simply replace fragment for <androidx.fragment.app.FragmentContainerView>. The fix, as of now, as stated by many google enginners in this bug thread is to change your code in your activity:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
Important! There are known issues with different versions of FragmentContainerView. See the changelog before using. Read through bug fixes and use a recent version of the library.
For now, you should also declare dependency on Fragment 1.2.0-beta02 as it includes a fix for this use case.
implementation "androidx.fragment:fragment:1.2.0-beta02"
Version 1.2.0-beta02
October 11, 2019
Bug fixes
Fixed an issue where Fragment's
onInflate()did not receive proper attributes fromFragmentContainerView, breaking cases such asNavHostFragment. (b/142421837)
Source: https://developer.android.com/jetpack/androidx/releases/fragment#1.2.0-beta02
The NavigationBasicSample has been updated to 2.2.0-alpha01 but is still using the fragment tag. The NavigationAdvancedSample shows the use of the FragmentContainerView, but the nav graph is inflated in the code (they have several different graphs) and the corresponding host fragment is added to the FragmentContainerView. So I'd say at this time we should ignore the warning if we want automatic inflation.
using Java
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.nav_host_fragment);
navController = navHostFragment.getNavController();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With