Android 导航图不显示起始片段

Android Navigation Graph not displaying start fragment

我 运行 陷入困境,调试应该是一个简单的问题:我有一个带有一个 activity 的应用程序,其中包含一个导航图,它应该在启动时显示一个片段。但事实并非如此。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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"
    tools:context=".MainActivity"
    >

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"/>

</FrameLayout>

res/navigation/nav_graph.xml

<?xml version="1.0" encoding="utf-8"?>
<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/listFragment"
    >

    <fragment
        android:id="@+id/listFragment"
        android:name="org.example.my_app.ui.ListFragment"
        android:label="fragment_list"
        tools:layout="@layout/fragment_list"
        >
        <action
            android:id="@+id/action_listFragment_to_detailFragment"
            app:destination="@id/detailFragment"
            />
    </fragment>
    <fragment
        android:id="@+id/detailFragment"
        android:name="org.example.my_app.ui.DetailFragment"
        android:label="fragment_detail"
        tools:layout="@layout/fragment_detail"
        />
</navigation>

fragment_list.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ListFragment"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This should be visible"
        />

</FrameLayout>

ListFragment.kt

class ListFragment : Fragment(R.layout.fragment_list)

尽管设置非常简单,但我看到一个空白屏幕(只是一个应用程序栏)并且添加到 ListFragment class init 的调试侦听器永远不会被调用。为什么我的 navGraph 没有初始化片段的实例?

文档:

NavHostFragment provides an area within your layout for self-contained navigation to occur.

您没有通过 android:name 属性在 FragmentContainerView 中将片段占位符声明为 NavHostFragment;因此导航不会发生。

<androidx.fragment.app.FragmentContainerView
    ....
    android:name="androidx.navigation.fragment.NavHostFragment"