首页 > 解决方案 > 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);

    }

标签: androidandroid-fragmentsmenuandroid-toolbarandroid-navigation

解决方案


推荐阅读