android - Android 工具栏 - 片段中的 NavigationUI.setupWithNavController
问题描述
我正在尝试使用 NavigationUI 和工具栏的菜单来浏览片段。
我按照谷歌的指南如下: https ://developer.android.com/guide/navigation/navigation-ui?hl=en#support_app_bar_variations
但是,我无法使用工具栏的菜单从片段 A 导航到片段 B
我的片段有自己的工具栏和菜单,如下 XML
<com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:menu="@menu/menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.appbar.AppBarLayout>
我的工具栏菜单是
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/fragmentA"
android:title="@string/fragmentA" />
<item
android:id="@+id/fragmentB"
android:title="@string/fragmentB" />
</menu>
导航主机在我的主要活动中,导航图如下:
<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/user"
app:startDestination="@id/userList">
<fragment
android:id="@+id/fragmentA"/>
<fragment
android:id="@+id/fragmentB"/>
</navigation>
在我的片段中,我有以下代码来设置 NavigationUI 导航
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
NavController navController = Navigation.findNavController(view);
AppBarConfiguration appBarConfiguration =
new AppBarConfiguration.Builder(navController.getGraph()).build();
Toolbar toolbar = view.findViewById(R.id.toolbar);
NavigationUI.setupWithNavController(
toolbar, navController, appBarConfiguration);
}
解决方案
推荐阅读
- c++ - 调用复制构造函数而不是移动构造函数?
- javascript - 如何根据猫鼬中的对象ID列表删除数组项?
- scala - Spark Scala - 时间戳的最小差异
- c# - 从同一输入中分离 3 个不同的值
- terraform - Terraform 将公共 IP 与自动生成的 node_resource_group 关联
- oracle - Oracle APEX 交互式网格新行不可编辑
- sparql - SPARQL:如何列出与通用限制不矛盾的所有可能性
- javascript - 带有ajax的Django模板变量
- android - Flutter firebase_messaging:^6.0.13 失败,但有异常:
- javascript - sh: ng: command not found 部署时无法在 openshift 上执行启动脚本