问题描述
我将Android导航组件与底部导航一起使用,棉绒给出了有关将<fragment>
标记替换为FragmentContainerView
的警告,但是当我替换时,findNavController
无法正常工作时,它给我有关它没有错误的错误NavController设置为
I'm using Android Navigation Component with bottom navigation, lint gives a warning about replacing the <fragment>
tag with FragmentContainerView
but when i replaced, findNavController
is not working it gives me error about it does not have a NavController set on
片段
<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)
}
推荐答案
根据此问题 ,当使用FragmentContainerView
时,您需要使用findFragmentById()
查找NavController
,而不是在onCreate()
中使用findNavController()
:
As per this issue, when using FragmentContainerView
, you need to find the NavController
using findFragmentById()
rather than using findNavController()
when in 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
).
This is because findNavController(R.id.nav_host_fragment)
relies on the Fragment's View to already be created which isn't the case when using FragmentContainerView
(as it uses a FragmentTransaction
under the hood to add the NavHostFragment
).
这篇关于使用findNavController的FragmentContainerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!