SetupWithNavController 不适用于工具栏 [英] SetupWithNavController does't work for toolbar

查看:80
本文介绍了SetupWithNavController 不适用于工具栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to bind toolbar to navigation controller, for that I am using the following code:

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

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

and in the menu file, I provided the id of the fragment to which app should navigate like this:

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

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

and I have a simple navigation graph file like this:

<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>

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

Does anyone have experience or can suggest how I can fix the issue and is toolbar supported by the navigation component?

任何示例代码或参考?

推荐答案

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

Finally, I found a solution thanks to Google CodeLab

我缺少的是:

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

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

Plus if you want to have back button support you need in onCreate method to add:

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

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

Basically, In my understanding just bt providing id of the correct fragment for the menu item and calling setupWithNavController should work, but that assumption was not correct, or maybe in the current version (1.0.0-alpha07) Google guys changed something. So now it is working fine.

如果您发现有一种方法可以缩短:) 或更好:) 请告诉我.

If you see that there is a way to do it shorter :) or better :) let me know.

这篇关于SetupWithNavController 不适用于工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆