我正在尝试将
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)
}
}