NavHostFragment 初始化导致 NullPointerException

NavHostFragment initialization results in NullPointerException

我试图在我的 MainActivity.kt 文件中设置一个 navHostFragment,但下面的代码导致错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lunchtray/com.example.lunchtray.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
class MainActivity : AppCompatActivity() {

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val navHostFragment = supportFragmentManager // NULL CANNOT BE CAST TO NON NULL TYPE
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        setupActionBarWithNavController(navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}

activity_main.xml布局文件:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <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"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

我做错了什么? SO 上存在类似的问题,但它们涉及使用菜单 ID 或从片段中初始化 navHostFragment,这是一个更直接的情况,我不明白为什么任何值都应该为 null。

您忘记调用 setContentView(R.layout.activity_main),这意味着您没有 FragmentContainerView 并且其中没有片段,因此 findFragmentById(R.id.nav_host_fragment) returns 为空。

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

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

作为替代方案,您也可以调用 AppCompatActivity construct that takes a LayoutRes,它会自动为您调用 setContentView 作为 super.onCreate() 的一部分:

class MainActivity : AppCompatActivity(R.ayout.activity_main) {