如何在Jetpack Compose中为选中的底部导航项图标添加圆角背景
你想要实现如图所示的底部导航项选中时图标周围的圆角形状,当前使用的BottomNavigationItem代码如下:

当前代码:
BottomNavigationItem( selected = selected, onClick = {...} icon = { Icon( imageVector = if (selected) navItem.iconFilled else navItem.iconOutlined, contentDescription = navItem.route, // modifier = Modifier.background(Color.DarkGray, shape = RoundedCornerShape(10.dp)).padding(10.dp) ) }, label = {...}, selectedContentColor = MaterialTheme.colors.onPrimary, unselectedContentColor = MaterialTheme.colors.onPrimary.copy(0.4f) ) } }
实现方法
只需要给Icon的modifier添加条件判断,仅在选中状态时显示圆角背景即可,同时保持未选中状态的内边距一致,避免布局跳动:
BottomNavigationItem( selected = selected, onClick = {...}, icon = { Icon( imageVector = if (selected) navItem.iconFilled else navItem.iconOutlined, contentDescription = navItem.route, modifier = if (selected) { Modifier .background(Color.DarkGray, shape = RoundedCornerShape(10.dp)) .padding(10.dp) } else { Modifier.padding(10.dp) } ) }, label = {...}, selectedContentColor = MaterialTheme.colors.onPrimary, unselectedContentColor = MaterialTheme.colors.onPrimary.copy(0.4f) )
额外调整建议
- 可以根据你的设计需求修改
RoundedCornerShape的数值(比如改成12.dp),或者替换背景颜色为主题色(比如MaterialTheme.colors.primary) - 内边距数值也可以根据图标大小灵活调整,保证背景和图标适配
内容的提问来源于stack exchange,提问作者Kofi k
相关产品推荐
相关产品推荐

