FragmentContainerView as NavHostFragment
Due to this bug-report: https://issuetracker.google.com/issues/142847973
This is the only way (currently):
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
(Java):
NavHostFragment navHostFragment =
(NavHostFragment) getSupportFragmentManager()
.findFragmentById(R.id.my_nav_host_fragment);
NavController navController = navHostFragment.getNavController();
August 2020 update
Here is the solution recommended by the official Android documentation.
Kotlin version:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
Java version:
NavHostFragment navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();
I quote the doc:
When creating the NavHostFragment using FragmentContainerView or if manually adding the NavHostFragment to your activity via a FragmentTransaction, attempting to retrieve the NavController in onCreate() of an Activity via Navigation.findNavController(Activity, @IdRes int) will fail. You should retrieve the NavController directly from the NavHostFragment instead.
The bug-report reported by Ove Stoerholt will not be fixed. You can see here the "Won't Fix (Infeasible)" status.