BottomNavigationBar 不适用于 ViewBinding 和 NavigationView

问题描述 投票:0回答:0

我正在尝试将

BottomNavigationBar
 ViewBinding
NavigationView
一起使用。但是当我点击
BottomNavigationBar 
中的图标时,它不会导航到相应的
fragment
甚至更改
AppBar
名称。

activity_main

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
        app:navGraph="@navigation/my_nav" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fragmentContainerView"
        android:id="@+id/bottomNavigation"
        app:menu="@menu/bottom_nav_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

class MainActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private val navController by lazy {
        binding.fragmentContainerView.getFragment<NavHostFragment>().navController
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        

         setUpActionBarWithNavigation()
        setUpBottomBarWithNavigation()

        binding.bottomNavigation.setOnItemSelectedListener { true }

    }

    private fun setUpBottomBarWithNavigation() {
       binding.bottomNavigation.setupWithNavController(navController)
    }

    private fun setUpActionBarWithNavigation() {

        val appBarConfiguration = AppBarConfiguration(setOf(
            R.id.feedFragment,
            R.id.favoritesFragment
        ))

        setupActionBarWithNavController(navController,appBarConfiguration)



    }


}
android kotlin android-jetpack bottomnavigationview android-viewbinding
© www.soinside.com 2019 - 2024. All rights reserved.