首页 > 解决方案 > 获取 NavHostFragment 的第一个子级

问题描述

基于这个答案,我尝试了解决方案,但我将片段设为空。

如何使用导航架构组件查找子片段

MainActivity.kt我有这个代码。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    supportActionBar?.title = "Product List"
  println(nav_host_fragment.childFragmentManager.findFragmentById(R.id.productListFragment))
}

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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="match_parent">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_host_fragment" />

</androidx.constraintlayout.widget.ConstraintLayout>

nav_host_fragment.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" android:id="@+id/products"
        app:startDestination="@id/productListFragment">

    <fragment
            android:id="@+id/productListFragment"
            android:name="ProductListFragment"
            android:label="ProductListFragment" >
    </fragment>

</navigation>

横向思维

还是我必须在ProductListFragment.kt->内工作onViewCreated并从那里进行活动。

标签: android

解决方案


推荐阅读