如何在Jetpack Compose Material 3中修改NavigationBar高度?
方法一:调整官方NavigationBar的内边距与元素尺寸
直接修改官方NavigationBar高度时,重叠问题源于组件默认的内部padding和元素尺寸。通过以下步骤可解决:
- 给
NavigationBar设置目标高度,并减少内部上下内边距 - 缩小图标尺寸、调整文字大小,同时优化
NavigationBarItem的内部间距
修改后的核心代码片段:
Scaffold( bottomBar = { NavigationBar( containerColor = MainWhite, modifier = Modifier.height(60.dp), // 设置自定义高度 contentPadding = PaddingValues(vertical = 4.dp) // 减少上下内边距 ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination listOfNavItems.forEach { navItem -> val selected = currentDestination?.hierarchy?.any { it.route == navItem.route } == true NavigationBarItem( selected = selected, onClick = { /* 保留原有导航逻辑 */ }, icon = { Icon( if (selected) navItem.filledIcon else navItem.outlinedIcon, contentDescription = navItem.description, modifier = Modifier.size(24.dp), // 缩小图标尺寸 tint = if (selected) MainTurquoise else MainGrey ) }, label = { Text( text = navItem.label, style = MaterialTheme.typography.bodyLarge, fontSize = 11.sp, // 进一步缩小字号 fontWeight = FontWeight.SemiBold, color = if (selected) MainTurquoise else MainGrey ) }, colors = NavigationBarItemDefaults.colors( indicatorColor = MainWhite, // 其余颜色配置保留原有设置 ), alwaysShowLabel = true // 确保标签始终显示,避免布局跳动 ) } } } ) { paddingValues -> // 原有NavHost代码不变 }
方法二:自定义底部导航栏布局(完全控制高度)
如果官方组件的约束难以满足需求,可直接用Row+Column自定义导航栏,完全掌控高度、内边距和元素排列:
Scaffold( bottomBar = { Row( modifier = Modifier .height(60.dp) // 自定义高度 .fillMaxWidth() .background(MainWhite), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination listOfNavItems.forEach { navItem -> val selected = currentDestination?.hierarchy?.any { it.route == navItem.route } == true Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .weight(1f) .clickable { // 保留原有导航逻辑 navController.navigate(navItem.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } ) { Icon( imageVector = if (selected) navItem.filledIcon else navItem.outlinedIcon, contentDescription = navItem.description, modifier = Modifier.size(24.dp), tint = if (selected) MainTurquoise else MainGrey ) Spacer(modifier = Modifier.height(2.dp)) // 自定义图标与文字间距 Text( text = navItem.label, style = MaterialTheme.typography.bodyLarge, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = if (selected) MainTurquoise else MainGrey ) } } } } ) { paddingValues -> // 原有NavHost代码不变 }
注意事项
- 调整官方组件高度时,需保证设置的高度不小于图标+文字+必要间距的总高度,否则仍可能出现重叠
- 自定义布局的优势是无默认约束,适合高度定制化的场景
内容的提问来源于stack exchange,提问作者Lorenzo Toro
相关产品推荐
相关产品推荐

