Two NavHosts with their own NavControllers and NavGraphs (Navigation Component) //Android Kotlin Dev Diary

Written by

on

in

, ,

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)

    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!!

Related Posts

About the author:

Catzie Avatar

The homo sapiens behind these blog posts is “Catzie“

Explore my top blog posts:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *