【发布时间】:2022-12-27 23:30:58
【问题描述】:
I have the following code
val navigation: BottomNavigationView = findViewById(R.id.navigation)
val navController = findNavController(R.id.nav_host_fragment_activity_main)
navController.graph = navController.createGraph(startDestination = R.id.navigation_home) {
fragment<HomeFragment>(R.id.navigation_home) {
label = getString(R.string.title_home)
}
fragment<DashboardFragment>(R.id.navigation_dashboard) {
label = getString(R.string.title_dashboard)
}
}
navigation.setupWithNavController(navController)
And the bottom Bar menu is
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/title_home"/>
<item
android:id="@+id/navigation_dashboard"
android:icon="@drawable/ic_dashboard_black_24dp"
android:title="@string/title_dashboard"/>
</menu>
which works fine.
However, the createGraph complaint asked me to Use routes to create your NavGraph instead
So I change my code to the following
val navigation: BottomNavigationView = findViewById(R.id.navigation)
val navController = findNavController(R.id.nav_host_fragment_activity_main)
navController.graph = navController.createGraph(startDestination = navRoutes.home) {
fragment<HomeFragment>(navRoutes.home) {
label = getString(R.string.title_home)
}
fragment<DashboardFragment>(navRoutes.dashboard) {
label = getString(R.string.title_dashboard)
}
}
navigation.setupWithNavController(navController)
where
object navRoutes {
const val home = "home"
const val dashboard = "dashboard"
}
This compiles fines and no more complaints in createGraph function. However, the bottom bar doesn't function anymore.
My guess is because the Menu (in XML) of the Bottom bar is not pointing to the new String-based route.
How can I link the Bottom Bar Menu with the String-base route of my Navigation Graph?
【问题讨论】:
标签: android android-navigation-graph android-bottomnav android-bottomappbar android-components