【问题标题】:Using Android navigation component with single activiy, layout drawer and toolbars inside fragments在 Fragment 中使用带有单个活动、布局抽屉和工具栏的 Android 导航组件
【发布时间】:2019-08-18 18:48:24
【问题描述】:

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

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

【问题讨论】:

    标签: android navigation-drawer android-navigation android-architecture-navigation android-navigationview


    【解决方案1】:

    唯一的要求是在调用setSupportActionBar() 之后再调用setupActionBarWithNavController。如果您在 Fragment 中执行此操作,则只需在此之后直接调用 setupActionBarWithNavController

    例如,在您的 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)
    }
    

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

    【讨论】:

    • 这可能是一个愚蠢的问题,但这会重置导航回栈吗?例如,如果我在那个片段中点击背面,它会知道返回哪里吗?
    • 它是同一个 NavController 实例,所以它会知道去哪里。
    • 有点晚了,但是我发现如上图在一个fragment的onViewCreated方法中调用setSupportActionBar方法,往往会导致action bar的标题在事务动画之前从显然不是特别理想的前一个片段。经过相当多的搜索后,我无法找到有关如何在单个活动中通过导航片段链接的多个片段设置不同工具栏的太多信息。这是解决方案中提供的方法的已知问题吗?
    • @JoshHardman - 听起来你遇到了this issue,这表明根本不要使用android:label,而是在你的工具栏中使用一个固定的标题(因为你永远不希望它从它的无论如何,在 Fragment 的布局中使用工具栏时,无论如何都是固定值)。
    • 感谢伊恩的快速回复,我一直在观看您的一些演讲,试图了解这一点!我之前确实尝试过删除标签属性,这似乎不太奏效,但我会再尝试一下
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多