Jetpack compose:自定义单选按钮组,实现分段按钮

Har*_*Xie 3 android android-jetpack-compose android-jetpack-compose-button

iOS 有这样的分段控件。在此输入图像描述 我想通过使用 jetpack compose 在 Android 中实现此功能,我检查了没有这样的内置功能,并且材料 3 中的 UI 现在不支持 jetpack compose。我能做些什么?完全自定义单选按钮?我知道我可以添加背景和文本之类的东西,但我怎样才能隐藏复选标记,使单选按钮看起来像一个按钮?或者我可以使用一些库来使用诸如分段控件之类的 UI?有人能给我一些提示吗?

Gab*_*tti 9

您可以使用应用 anRow来避免双边框。OutlinedButtonOffset

就像是:

    Row(
        modifier = Modifier
            .fillMaxWidth()
    ) {

        val cornerRadius = 16.dp
        var selectedIndex by remember { mutableStateOf(-1) }

        itemsList.forEachIndexed { index, item ->

            OutlinedButton(
                onClick = { selectedIndex = index },
                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)
                },
                shape = when (index) {
                    0 -> RoundedCornerShape(
                        topStart = cornerRadius,
                        topEnd = 0.dp,
                        bottomStart = cornerRadius,
                        bottomEnd = 0.dp
                    )
                    itemsList.size - 1 -> RoundedCornerShape(
                        topStart = 0.dp,
                        topEnd = cornerRadius,
                        bottomStart = 0.dp,
                        bottomEnd = cornerRadius
                    )
                    else -> RoundedCornerShape(
                        topStart = 0.dp,
                        topEnd = 0.dp,
                        bottomStart = 0.dp,
                        bottomEnd = 0.dp
                    )
                },
                border = BorderStroke(
                    1.dp, if (selectedIndex == index) {
                        Blue500
                    } else {
                        Blue500.copy(alpha = 0.75f)
                    }
                ),
                colors = if (selectedIndex == index) {
                    ButtonDefaults.outlinedButtonColors(
                        containerColor = Blue500.copy(alpha = 0.1f),
                        contentColor = Blue500
                    )
                } else {
                    ButtonDefaults.outlinedButtonColors(
                        containerColor = MaterialTheme.colorScheme.surface,
                        contentColor = Blue500
                    )
                }
            ) {
                Text("Button " + item)
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述