android - 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>
有没有人有经验或可以建议我如何解决这个问题以及导航组件是否支持工具栏?
任何示例代码或参考?
解决方案
我缺少的是:
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)中谷歌人改变了一些东西。所以现在它工作正常。
如果您发现有一种方法可以缩短 :) 或更好 :) 让我知道。
推荐阅读
- reactjs - 同一组件具有不同查询字符串的两条路由
- firebase-realtime-database - 为了重置 Firebase 实时数据库中的分数,我应该在 Cloud Scheduler Payload 中添加什么?
- serilog - appsettings.json 中的 serilog 配置中“使用”的目的是什么?
- javascript - 为什么这个 vuejs v-for 循环会抛出未定义的错误?
- javascript - npx babel-node foo 每次运行需要 10 秒
- java - JUnit 测试的默认工作目录 - 我们如何在 Eclipse 中一致地定义它?
- ionic-framework - 离子标签显示,但不切换到其他标签
- python - 如何使用 Python 准确复制 Windows cmd shell mkdir 的行为?
- c++ - 我不知道如何创建一个程序以数字/字母顺序打印出我的整数或字符串
- android - React native assembleRelease 无法使用 axios 获取数据