Issue
Is it possible to use Android Navigation component/graph in the single activity app in which each fragment has its own toolbar?
Also, container activity has a navigation drawer that needs setup with toolbar and navigation controller, but at the time of activity creation I don't have yet the toolbar.
I am using this code (called in onCreate)
private fun setupNavigation() {
// val toolbar = findViewById<Toolbar>(R.id.toolbar);
// setSupportActionBar(toolbar);
// supportActionBar!!.setDisplayHomeAsUpEnabled(true);
// supportActionBar!!.setDisplayShowHomeEnabled(true);
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout);
val navigationView = findViewById<NavigationView>(R.id.drawer_navigation_view);
val navController = Navigation.findNavController(this, R.id.navigation_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
NavigationUI.setupWithNavController(navigationView, navController)
navigationView.setNavigationItemSelectedListener(this)
}
But since I don't have toolbar at the time it throws an error (ActionBar.setTitle called on a null object).
Is it possible to have this, or I need to drop the idea to use navigation component in this case?
Solution
The only requirement is that you call setupActionBarWithNavController
after you call setSupportActionBar()
. If you're doing that in your Fragment, then just call setupActionBarWithNavController
directly after that.
For example, in your Fragment:
private fun onViewCreated(view: View, bundle: savedInstanceState) {
val toolbar = view.findViewById<Toolbar>(R.id.toolbar);
// Set the Toolbar as your activity's ActionBar
requireActivity().setSupportActionBar(toolbar);
// Find the activity's DrawerLayout
val drawerLayout = requireActivity().findViewById<DrawerLayout>(R.id.drawer_layout);
// Find this Fragment's NavController
val navController = NavHostFragment.findNavController(this);
// And set up the ActionBar
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
}
There's also a separate NavigationUI.setupWithNavController()
method that takes a Toolbar
. This would be appropriate if you aren't actually using any of the other ActionBar APIs.
Answered By - ianhanniballake
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.