BottomNavigationView 抛出 NullPointerException

BottomNavigationView throws NullPointerException

你好,我正在尝试使用导航组件实现 BottomNavigationView。我在构建它时使用了官方文档作为参考。但是当我 运行 项目时,我得到了 java.lang.NullPointerException...我似乎无法弄清楚我做错了什么

这是我的 MainActivity:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private lateinit var navController: NavController


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        setUpBottomNavigationBar()

    }

    private fun setUpBottomNavigationBar() {
        val navHostFragment = supportFragmentManager.findFragmentById(
            R.id.fragment_container
        ) as NavHostFragment
        navController = navHostFragment.navController

        // Setup the bottom navigation view with navController
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
        bottomNavigationView.setupWithNavController(navController)
    }

}

MainActivity 布局 res 文件:

 <fragment
        android:id="@+id/fragment_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation_view"/>


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation_menu" /> 

错误:

2022-05-02 14:28:58.746 5952-5952/com.example.dogexplorer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dogexplorer, PID: 5952
    java.lang.NullPointerException
        at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.kt:69)
        at androidx.navigation.ui.NavigationUI.setupWithNavController$lambda-6(NavigationUI.kt:602)
        at androidx.navigation.ui.NavigationUI.$r8$lambdawzEv9QqEZKdQFS1sQQy-bdQvgE(NavigationUI.kt)
        at androidx.navigation.ui.NavigationUI$$ExternalSyntheticLambda2.onNavigationItemSelected(D8$$SyntheticClass) .......

您需要在 fragment_container 添加导航图,以创建导航图右键单击 res 文件夹 -> 新建 android 资源文件 -> 类型:导航

app:navGraph="@navigation/your_navigation_graph"

文档 -> https://developer.android.com/guide/navigation/navigation-getting-started