FragmentContainerView 使用 findNavController [英] FragmentContainerView using findNavController

查看:91
本文介绍了FragmentContainerView 使用 findNavController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有底部导航的 Android 导航组件,lint 给出了关于用 替换 标记的警告,但是当我替换时,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() 而不是使用 findNavController() 来查找 NavControlleronCreate() 中:

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) 依赖于已经创建的 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).

这篇关于FragmentContainerView 使用 findNavController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆