I don't understand the way we get navController inside Activitiy

Viewed 39

I searched a lot and most people used this line of code to get navController in Activity:

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

I am wondering, why we can't just use, findViewById method of Activity to get FragmentContainerView.

1 Answers

If the thing you are looking for is FragmentContainerView then you can certainly use findViewById but if you want to access NavController then you have to use the methods exposed by the library.

// from fragments
Fragment.findNavController()
// from views
View.findNavController()
// from activity
Activity.findNavController(viewId: Int)
// from NavHostFragment
navHostFragment.navController
Related