I am trying to make a single-activity app because I’d like to easily share data across screen using, ideally one, or as few as possible ViewModels.
NavGraph 1
Host: Layout file of MainActivity
Destination(s): CreateLogFragment
NavGraph 2
Host: Layout file of CreateLogFragment
Destination(s): CreateLogFoodFragment, CreateLogNotesFragment
(CreateLogFragment has a BottomNavigationBar that switches between CreateLogFoodFragment and CreateLogNotesFragment)
The problem was that NavGraph 2 was not getting the correct NavHost and NavController in the CreateLogFragment class.
And the solution is to retrieve the NavHost in CreateLogFragment like so:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
1 2 3 4 5 6 7 |
val navHostFragment = childFragmentManager.findFragmentById(R.id.nav_host_create_log) as NavHostFragment val navController = navHostFragment.navController // Setup Bottom Nav val bottomNav: BottomNavigationView = binding.bottomNav bottomNav.setupWithNavController(navController) } |
I’d like to write a full tutorial on how to do this but I’m not sure if I could spare some time. If you’ve been reading my recent posts you’ll notice that I’m not able to put it so much effort in explaining everything. These days I’m always in a hurry to finish stuff. But I’ll still try!!