是否有可能在单个活动应用程序中使用Android导航组件/图形,其中每个片段都有自己的工具栏?
此外,容器活动有一个导航抽屉,需要使用工具栏和导航控制器进行设置,但是在创建活动时,我还没有工具栏。
我正在使用此代码(在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)
}
但是由于当时我没有工具栏,因此会引发错误(在空对象上调用了ActionBar.setTitle)。
是否有可能,或者在这种情况下我需要放弃使用导航组件的想法?
答案 0 :(得分:3)
唯一的要求是您在致电let
之后再致电setupActionBarWithNavController
。如果您要在Fragment中执行此操作,则只需在此之后直接调用setSupportActionBar()
。
例如,在您的片段中:
setupActionBarWithNavController
还有一个单独的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)
}
方法,该方法采用NavigationUI.setupWithNavController()
。如果您实际上并未使用任何其他ActionBar API,则这将是适当的。