Android 获取NavHostFragment的第一个子级
基于这个答案,我尝试了这个解决方案,但我得到的片段为空 在MainActivity.kt中,我有这个代码Android 获取NavHostFragment的第一个子级,android,Android,基于这个答案,我尝试了这个解决方案,但我得到的片段为空 在MainActivity.kt中,我有这个代码 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) supportActionBar?.title = "Product List" println(nav_ho
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
中工作,并从那里接触活动。我试图在onCreate中获取片段,但找不到方法。。。如果您想与activity进行通信,请在onViewCreated
中执行此操作更有意义。。。如果您想与活动进行交流,在onViewCreated
中进行交流更有意义。