首页 > 解决方案 > SetupWithNavController 不适用于工具栏

问题描述

我正在尝试将工具栏绑定到导航控制器,为此我使用以下代码:

NavigationUI.setupWithNavController(toolbar, NavHostFragment.findNavController(nav_host))

在菜单文件中,我提供了应用程序应该导航到的片段的 ID,如下所示:

<item
    android:id="@+id/menuFragment"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

我有一个简单的导航图文件,如下所示:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.vapoyan.myapplication.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >
        <action
            android:id="@+id/action_homeFragment_to_menuFragment"
            app:destination="@id/menuFragment" />
    </fragment>

    <fragment
        android:id="@+id/menuFragment"
        android:name="com.vapoyan.myapplication.MenuFragment"
        android:label="fragment_menu"
        tools:layout="@layout/fragment_menu" />
</navigation>

有没有人有经验或可以建议我如何解决这个问题以及导航组件是否支持工具栏?

任何示例代码或参考?

标签: androidkotlinandroid-architecture-componentsandroidx

解决方案


最后,感谢Google CodeLab ,我找到了解决方案

我缺少的是:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
     return NavigationUI.onNavDestinationSelected(item, NavHostFragment.findNavController(nav_host))
            || super.onOptionsItemSelected(item)
}

另外,如果您想获得后退按钮支持,则需要在onCreate方法中添加:

NavigationUI.setupWithNavController(toolbar, NavHostFragment.findNavController(nav_host))

基本上,在我的理解中,只是id为菜单项提供正确的片段并调用setupWithNavController应该可以工作,但这种假设是不正确的,或者可能在当前版本(1.0.0-alpha07)中谷歌人改变了一些东西。所以现在它工作正常。

如果您发现有一种方法可以缩短 :) 或更好 :) 让我知道。


推荐阅读