是否可以在每个片段都有自己的工具栏的单个活动应用程序中使用 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)。
是否有可能有这个,或者我需要放弃在这种情况下使用导航组件的想法?
唯一的要求是你打电话setupActionBarWithNavController
当你打电话之后setSupportActionBar()
。如果您在 Fragment 中执行此操作,则只需调用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()
方法需要一个Toolbar
。如果您实际上没有使用任何其他 ActionBar API,那么这将是合适的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)