FragmentContainerView using findNavController

As per this issue, when using FragmentContainerView, you need to find the NavController using findFragmentById() rather than using findNavController() when in onCreate():

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

This is because findNavController(R.id.nav_host_fragment) relies on the Fragment’s View to already be created which isn’t the case when using FragmentContainerView (as it uses a FragmentTransaction under the hood to add the NavHostFragment).

If you are using Fragment 1.4.0 or higher and View Binding, you can simply this considerably by using the getFragment() method:

val navController = binding.container.getFragment<NavHostFragment>().navController

Leave a Comment