尝试显示不在菜单中的片段时,导航抽屉 Activity 项目中的片段重叠

Fragments overlapping in Navigation Drawer Activity project when trying to display a fragment that isn't in the menu

我使用“Navigation Drawer Activity”模板创建了一个简单的项目。
当我尝试导航到不在导航菜单中的片段时,该片段出现在当前片段的顶部。
我正在使用它来导航到不在导航菜单中的片段我使用它:

FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction().replace(R.id.nav_host_fragment, nextFrag).commit();

所有 app_bar_main 和 content_main xml 文件与 android studio 生成的文件完全相同。

我在上面使用了“nav_host_fragment”,因为在我的 content_main 文件中我有:

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

我试着用另一个容器包裹它并使用它,但没有任何改变。

在使用 NavHostFragment 和导航组件时,您应该永远不要 使用 FragmentTransaction(事实上,即使您不使用,您永远无法替换 <fragment> 添加的片段。

相反,您应该遵循 Tie destinations to menu items 并将片段添加到 res/navigation/mobile_navigation.xml 文件中,并确保 menu.xml 文件项的 ID 与 android:id 匹配图表中的目的地。