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

Tri*_*ung 7 android-jetpack android-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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 11

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

.background(color = AnkiBlue100, shape = RoundedCornerShape(8.dp))
Run Code Online (Sandbox Code Playgroud)

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