Jetpack Compose中跳转DetailPage时BottomNavigation不隐藏如何解决?
问题说明
出现该问题的核心原因是Scaffold的bottomBar属性配置的底部导航是全局绑定在当前Scaffold容器上的,你将NavHost放在了Scaffold的内容区,所有路由跳转的页面都嵌套在这个Scaffold内部,因此默认所有页面都会显示底部导航。
效果示意:
- 带有BottomNavigation的MainPage页面:

- 从MainPage跳转进入的DetailPage页面:

解决方法
通过监听当前路由地址,动态判断是否需要显示底部导航即可,具体实现步骤如下:
1. 定义路由常量
区分需要显示底部导航的一级页面和不需要显示的二级页面:
object Routes { // 带底部导航的一级页面路由 const val MAIN_HOME = "main_home" const val MAIN_CATEGORY = "main_category" const val MAIN_MINE = "main_mine" // 不需要底部导航的二级页面路由 const val DETAIL_PAGE = "detail_page" }
2. 监听路由动态控制底部导航显示
在MainPage中监听当前路由,匹配需要显示底部导航的路由列表,动态控制Scaffold的bottomBar参数:
@Composable fun MainPage(navController: NavHostController) { // 监听当前路由栈变化 val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route // 配置需要显示底部导航的路由列表 val showBottomBarRoutes = listOf( Routes.MAIN_HOME, Routes.MAIN_CATEGORY, Routes.MAIN_MINE ) val isShowBottomBar = currentRoute in showBottomBarRoutes Scaffold( bottomBar = { // 仅匹配到一级路由时显示底部导航 if (isShowBottomBar) { BottomNavigation { // 底部导航Tab实现,示例为首页Tab BottomNavigationItem( selected = currentRoute == Routes.MAIN_HOME, onClick = { navController.navigate(Routes.MAIN_HOME) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } }, icon = { Icon(Icons.Default.Home, contentDescription = "首页") }, label = { Text("首页") } ) // 其余Tab项按业务需求补充即可 } } } ) { innerPadding -> NavHost( navController = navController, startDestination = Routes.MAIN_HOME, modifier = Modifier.padding(innerPadding) ) { // 一级页面配置 composable(Routes.MAIN_HOME) { HomePage( onJumpToDetail = { // 跳转到详情页,自动隐藏底部导航 navController.navigate(Routes.DETAIL_PAGE) } ) } composable(Routes.MAIN_CATEGORY) { CategoryPage() } composable(Routes.MAIN_MINE) { MinePage() } // 二级详情页配置 composable(Routes.DETAIL_PAGE) { DetailPage() } } } }
注意事项
如果你的路由携带参数,比如详情页路由为detail_page/{goodsId},需要做前缀匹配判断,或者通过destination.hierarchy处理嵌套导航的场景,避免匹配失败。
内容的提问来源于stack exchange,提问作者Li Zhenxin
相关产品推荐
相关产品推荐

