Jetpack Compose 中的 MaterialButtonToggleGroup

LN-*_*-12 12 android modifier android-button kotlin android-jetpack-compose

我想在 Jetpack Compose 中实现MaterialButtonToggleGroup。该组件如下所示(图片取自此处):

到目前为止,我得到了以下结果:

请注意,存在垂直蓝色边框旁边的垂直灰色边框。在原作中,要么同时出现彩色边框,要么同时出现灰色。为了看得更清楚,看一下这张带有超厚边框的图像:

如何实现两个按钮之间不存在垂直边框?我当前的代码如下所示:

    val cornerRadius = 8.dp

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
    ) {
        Spacer(modifier = Modifier.weight(1f))

        items.forEachIndexed { index, item ->
            OutlinedButton(
                onClick = { indexChanged(index) },
                shape = when (index) {
                    // left outer button
                    0 -> RoundedCornerShape(topStart = cornerRadius, topEnd = 0.dp, bottomStart = cornerRadius, bottomEnd = 0.dp)
                    // right outer button
                    items.size - 1 -> RoundedCornerShape(topStart = 0.dp, topEnd = cornerRadius, bottomStart = 0.dp, bottomEnd = cornerRadius)
                    // middle button
                    else -> RoundedCornerShape(topStart = 0.dp, topEnd = 0.dp, bottomStart = 0.dp, bottomEnd = 0.dp)
                },
                border = BorderStroke(1.dp, if(selectedIndex == index) { MaterialTheme.colors.primary } else { Color.DarkGray.copy(alpha = 0.75f)}),
                colors = if(selectedIndex == index) {
                    // selected colors
                    ButtonDefaults.outlinedButtonColors(backgroundColor = MaterialTheme.colors.primary.copy(alpha = 0.1f), contentColor = MaterialTheme.colors.primary)
                } else {
                    // not selected colors
                    ButtonDefaults.outlinedButtonColors(backgroundColor = MaterialTheme.colors.surface, contentColor = MaterialTheme.colors.primary)
                },
            ) {
                Text(
                    text = "Some text",
                    color = if(selectedIndex == index) { MaterialTheme.colors.primary } else { Color.DarkGray.copy(alpha = 0.9f) },
                    modifier = Modifier.padding(horizontal = 8.dp)
                )
            }
        }

        Spacer(modifier = Modifier.weight(1f))
    }
Run Code Online (Sandbox Code Playgroud)

Gab*_*tti 10

为了MaterialButtonToggleGroup防止出现双宽笔划,除了第一个将相邻笔划直接重叠绘制的子项之外,所有笔划都有一个负的 marginStart 。

使用相同的解决方案:

OutlinedButton(
    modifier = when (index) {
        0 ->
            Modifier
                .offset(0.dp, 0.dp)
                .zIndex(if (selectedIndex == index) 1f else 0f)
        else ->
            Modifier
                .offset((-1 * index).dp, 0.dp)
                .zIndex(if (selectedIndex == index) 1f else 0f)
    },
    // Your code here
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述