在片段内使用带有单个活动、布局抽屉和工具栏的 Android 导航组件

dan*_*ela 4 android navigation-drawer android-navigation android-navigationview android-architecture-navigation

是否可以在每个片段都有自己的工具栏的单个活动应用程序中使用 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)
}
Run Code Online (Sandbox Code Playgroud)

但是由于我当时没有工具栏,它会引发错误(在空对象上调用 ActionBar.setTitle)。

是否有可能有这个,或者我需要放弃在这种情况下使用导航组件的想法?

ian*_*ake 8

唯一的要求是在调用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)
}
Run Code Online (Sandbox Code Playgroud)

还有一个单独的NavigationUI.setupWithNavController()方法需要一个Toolbar. 如果您实际上没有使用任何其他 ActionBar API,这将是合适的。