I promise that I will never touch fragment transactions with my bare hands. Except when absolutely necessary.
With that promise, enter Navigation Architecture Component. Navigation architecture component was introduced during io18, it promises to make our lives easier and reduce development time.
In this short article, we look at the role of Activity when using the Navigation architecture component.
- Navigation host (NavHost). The architecture component has a special fragment called NavHost fragment which is responsible for saving and restoring your navigation stack. The the activity hosts this special fragment and inflate it at run time.
- Global Navigation UI. In the case where you have global navigation UI like NavigationView or BottomNavigation, the Activity also holds this global navigation UI and if you decide to us the Navigation Architecture component UI, you can set up your global navigations with few lines of code.
Setup Global Navigation in Activity:
First of all, you need access to the navigation controller, you can get the navigation controller from the activity as shown below:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
Using NavigatonView:
When using navigation view, use the following code below and setup the navigations view with the NavigationController:
val navigationView = findViewById(R.id.nav_view)
navigationView.setupWithNavController(navigationController)
Using BottomNavigation:
val bottomNavigation = findViewById(R.id.bottom_nav)
bottomNavigation.setupWithNavController(navigationController)
Note: For automatic configuration, use the same id for both your navigation actions and menu items for the NavigationView or BottomNavigation menu. The navigation ui will automatically configure the actions for you
Conclusion
Since the introduction of the Navigation architecture component in May this year, the concept of single activity app is fast becoming the feature. But can we entire build our app on a single activity. I don’t think so, this can only happen when a fragment is able to do all the things an activity can do, including setting up the windows toolbar and taking fullscreen with fewest lines of code. Until then, single activity app is a dream yet to come through.