Jetpack Compose BottomNavigation自定义异常:样式与背景问题求助
问题解决方案
1. 移除白色背景框
BottomNavigationItem默认在选中时会应用Material主题的默认背景色,这就是你看到的白色框。同时原代码中BottomNavigation的padding会导致边缘透出父布局颜色,调整方案如下:
- 将
padding移到BottomNavigation外层的Box中,避免背景透色 - 通过
modifier直接覆盖BottomNavigationItem的默认背景,自定义选中状态样式
2. 让文本样式生效
BottomNavigationItem会对label应用默认的文本样式,覆盖了你自定义的Text14,需要合并默认样式与自定义样式,保留选中状态的颜色逻辑同时应用你的字体属性。
修改后的完整代码
@Composable fun BottomNavBar( backStackEntryState: State<NavBackStackEntry?>, navController: NavController, bottomNavItems: List<NavigationItem> ) { Box( modifier = Modifier .fillMaxWidth() .padding(Dimen10, Dimen20, Dimen10, Dimen20) ) { BottomNavigation( backgroundColor = DarkGray.copy(alpha = 0.6f), modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(Dimen13)) ) { bottomNavItems.forEach { item -> val isSelected = item.route == backStackEntryState.value?.destination?.route BottomNavigationItem( icon = { Icon( painter = painterResource(id = item.icon.orZero()), contentDescription = stringResource(id = item.title) ) }, label = { Text( text = stringResource(id = item.title), // 合并默认样式与自定义样式,保留颜色继承逻辑 style = LocalTextStyle.current.merge(Text14) ) }, selectedContentColor = Color.White, unselectedContentColor = Color.White, alwaysShowLabel = true, selected = isSelected, onClick = { navController.navigate(item.route) { navController.graph.startDestinationRoute?.let { route -> popUpTo(route = route) { saveState = true } } launchSingleTop = true restoreState = true } }, // 自定义选中/未选中背景,覆盖默认样式 modifier = Modifier .background(if (isSelected) DarkGray else Color.Transparent) .clip(RoundedCornerShape(Dimen13)) ) } } } }
额外检查建议
- 确认
Text14的样式定义未设置固定颜色,让它自动继承选中状态的颜色:val Text14 = TextStyle( fontSize = 14.sp, fontWeight = FontWeight.Medium // 不要添加color属性 ) - 如果样式仍不生效,可以直接在
Text组件中明确指定属性:Text( text = stringResource(id = item.title), fontSize = 14.sp, fontWeight = FontWeight.Medium, color = LocalContentColor.current )
内容的提问来源于stack exchange,提问作者R0ck
相关产品推荐
相关产品推荐

