如何在 Jetpack Compose 中将自定义选项卡指示器设为圆条

How to make custom tab indicator to be a rounded bar in Jetpack Compose

下图是我想要达到的效果。我希望选项卡指示器是一个短圆条。

我查阅了 TabRowDefaults.Indicator() 的实现,然后自己做了一个。我刚刚尝试添加 clip() 修饰符,但它没有用。我尝试更改修饰符的顺序,但仍然没有成功。

这是我的代码实现:

@Composable
fun TabLayout(
    tabItems: List<String>,
    content: @Composable () -> Unit
) {
    var tabIndex by remember { mutableStateOf(0) }
    Column {
        ScrollableTabRow(
            selectedTabIndex = tabIndex,
            edgePadding = 0.dp,
            backgroundColor = MaterialTheme.colors.background,
            contentColor = Blue100,
            indicator = { tabPositions ->
                Box(
                    modifier = Modifier
                        .tabIndicatorOffset(tabPositions[tabIndex])
                        .height(4.dp)
                        .clip(RoundedCornerShape(8.dp)) // clip modifier not working
                        .padding(horizontal = 28.dp)
                        .background(color = AnkiBlue100)
                )
            },
            divider = {},
        ) {
            tabItems.forEachIndexed { index, item ->
                Tab(
                    selected = tabIndex == index,
                    onClick = { tabIndex = index },
                    selectedContentColor = Blue100,
                    unselectedContentColor = Gray200,
                    text = {
                        Text(text = item, fontFamily = fontOutfit, fontSize = 18.sp)
                    }
                )
            }
        }
        Divider(
            color = Gray50,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 4.dp)
        )
        content()
    }
}

您在 Modifier.clipModifier.background 之间应用了 Modifier.padding,因此舍入实际上应用于透明填充。需要移动clip前面的padding,或者指定带背景的形状:

.background(color = AnkiBlue100, shape = RoundedCornerShape(8.dp))

中详细了解为什么修饰符的顺序很重要