使用findNavController的FragmentContainerView

问题描述 投票:0回答:1

我正在将Android导航组件与底部导航一起使用,棉绒给出了有关将<fragment>标记替换为FragmentContainerView的警告,但是当替换的findNavController无法正常工作时,它会提示我有关未设置NavController的错误

片段

<androidx.fragment.app.FragmentContainerView
            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:navGraph="@navigation/mobile_navigation" />

活动

val navController = findNavController(R.id.nav_host_fragment)

    val appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.navigation_classes, R.id.navigation_schedule, R.id.navigation_settings
        )
    )
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
}
android android-fragments android-navigation
1个回答
0
投票

根据this issue,在使用FragmentContainerView时,需要在NavController中使用findFragmentById()而不是在findNavController()中找到onCreate()

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

这是因为findNavController(R.id.nav_host_fragment)依赖于已经创建的片段视图,而使用FragmentContainerView则不是这种情况(因为它在幕后使用FragmentTransaction来添加NavHostFragment)。

© www.soinside.com 2019 - 2024. All rights reserved.