You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Jetpack Compose实现TabLayout选中标签背景色切换

实现选中Tab的背景色切换效果

要实现选中Tab显示独立背景色、切换时自动恢复原Tab背景的效果,只需要根据selected状态给Tab的modifier动态设置背景色即可,修改后的完整代码如下:

@ExperimentalPagerApi
@Composable
fun TableLayout(navController: NavController) {
    var tabIndex by remember { mutableStateOf(0) }
    val tabs = listOf("Basic", "Medium", "Hard")
    
    // 定义选中和未选中Tab的背景色
    val selectedTabBg = Color(123, 31, 162)
    val unselectedTabBg = Color.Transparent

    Column(
        modifier = Modifier
            .width(100.dp)
            .height(140.dp)
            .background(Color(153, 50, 204))
            .padding(top = 8.dp)
    ) {
        tabs.forEachIndexed { index, title ->
            val selected = tabIndex == index
            Tab(
                text = { Text(title, color = Color.White, textAlign = TextAlign.Start) },
                selected = selected,
                onClick = {
                    tabIndex = index
                    when (index) {
                        0 -> navController.navigate(Destinations.Basic)
                        1 -> navController.navigate(Destinations.Medium)
                        2 -> navController.navigate(Destinations.Hard)
                    }
                },
                // 根据选中状态动态设置背景色
                modifier = Modifier
                    .fillMaxWidth()
                    .background(if (selected) selectedTabBg else unselectedTabBg)
                    .padding(vertical = 8.dp, horizontal = 12.dp)
            )
        }
    }
}

关键修改说明

  • 新增selectedTabBg和unselectedTabBg常量,统一管理背景色,后续调整样式更便捷
  • 给每个Tab添加modifier,通过selected状态判断切换背景色:选中时使用深色紫色,未选中时用透明色(继承父布局背景)
  • 调整Tab的内边距,让背景色区域和文本的布局更协调

内容的提问来源于stack exchange,提问作者PurpleRabbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:45:11