[英]Android Navigation Graph not displaying start fragment
我正在调试一个简单的问题:我有一个包含一个活动的应用程序,其中包含一个导航图,它应该在启动时显示一个片段。 但事实并非如此。
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
类 init 中的调试侦听器。 为什么我的navGraph
初始化片段的实例?
文档:
NavHostFragment 在您的布局中提供一个区域,用于进行自包含导航。
您缺少通过android:name
属性在FragmentContainerView
中将片段占位符声明为NavHostFragment
; 因此导航不会发生。
<androidx.fragment.app.FragmentContainerView
....
android:name="androidx.navigation.fragment.NavHostFragment"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.