Navigation Activity xxxxxx does not have a NavController set on 2131230958

需求:Navigation 与 BottomNavigationView 一起使用

运行报错如下:

Caused by: java.lang.IllegalStateException: Activity package.activity.MainActivity@2e79c760 does not have a NavController set on 2131230958

报错代码 val navController = findNavController(R.id.nav_host_fragment) :

    private fun initNavigation() {
        //获取Navigation的导航控制器 NavController
        val navController = findNavController(R.id.nav_host_fragment)
        //把BottomNavigationView与NavController绑定。
        binding.bottomNavView.setupWithNavController(navController)
    }

定义在布局中的代码:

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

解决方式有两种,选择其中一个即可解决,建议选择第一个。

解决方式1,修改获取NavController的方式:

    private fun initNavigation() {
        //获取Navigation的导航控制器 NavController
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        //把BottomNavigationView与NavController绑定。
        binding.bottomNavView.setupWithNavController(navController)
    }

解决方式2,修改xml文件,把androidx.fragment.app.FragmentContainerView 改为 fragment :

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

发生问题的原因:
使用 FragmentContainerView 创建 NavHostFragment,或通过 FragmentTransaction 手动将 NavHostFragment 添加到您的 Activity 时,尝试通过 Navigation.findNavController(Activity, @IdRes int) 检索 Activity 的 onCreate() 中的 NavController 将失败。您应改为直接从 NavHostFragment 检索 NavController。

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

你可能感兴趣的:(Android,NavController)