我想用3项实现一个BottomNavBar。每个导航到一个新的navGraph。(嵌套导航)
Home = "HomeGraph“
探索= "ExploreGraph“
Profile = "ProfileGraph“
HomeGraph:
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.addHomeGraph(navController: NavHostController) {
navigation(
startDestination = "feed",
route = "HomeGraph"
) {
composable(
route = "feed"
) {
}
composable(
route = "comments"
) {
}
}
}我的BottomNavBar在这3张图之间导航:
@Composable
fun BottomNavigationBar(navController: NavController) {
val items = listOf(
BottomNavigationItem.HomeGraph,
BottomNavigationItem.ExploreGraph,
BottomNavigationItem.ProfileGraph
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
BottomNavigation() {
Row(horizontalArrangement = Arrangement.Center) {
items.forEach { item ->
BottomNavigationItem(
icon = {
if (currentRoute == item.route) {
Icon(
painterResource(id = item.iconPressed),
contentDescription = item.title
)
} else {
Icon(
painterResource(id = item.iconNormal),
contentDescription = item.title
)
}
},
selectedContentColor = MaterialTheme.colors.primary,
unselectedContentColor = MaterialTheme.colors.onSurface,
alwaysShowLabel = false,
selected = currentRoute == item.route,
onClick = {
navController.navigate(item.route) {
navController.graph.startDestinationRoute?.let { route ->
popUpTo(route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
}
}现在的问题是,我的“家”BottomNav图标并没有改变原因“选择”从来不是真的。
selected = currentRoute == item.route,如何检查我是否仍然在同一个navigationGraph上?因此,当我按下"HomeGraph“(例如”提要“或”注释“)时,它仍然应该表示我的BottomNavBar上的"Home”图标。
"feed“和”注释“有一个共同之处,即他们的父NavGraph被称为"HomeGraph",我如何检查这一点呢?
换句话说:我想要和Instagram一样的BottomNavBar行为
发布于 2022-09-11 04:49:46
与其匹配navBackStackEntry?.destination?.route,不如在NavDestination的层次结构中寻找您的路径。
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination然后在你的forEach中:
val selected = currentDestination?.hierarchy?.any { it.route == item.route } == truehttps://stackoverflow.com/questions/73670132
复制相似问题