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

在Jetpack Compose中实现不使用Radio Button的切换按钮组

问题原因

你当前按钮全部禁用是两处逻辑错误导致的:

  • 状态变量selected的初始值设为了"Android",但你的按钮选项列表里没有对应值,初始状态下两个按钮的text == selected判断结果都为false
  • 你把Button的enabled属性绑定到了text == selected,只有被选中的按钮才会处于启用状态,未选中按钮直接被禁用,自然无法点击切换

修正方案

你不需要依赖enabled属性区分选中状态,只要通过按钮的颜色、边框等样式区分选中/未选中即可,逻辑上只需要保证点击按钮时更新selected的取值就行。修正后的完整代码如下:

MovieSpotterTheme() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        @Composable
        fun MaterialButtonToggleGroup() {
            val buttonGroup = listOf("Popular Movies", "Search Movies")
            // 初始值设置为列表第一个选项,保证初始有选中项
            var selected by remember { mutableStateOf(buttonGroup.first()) }

            val onSelectedChange = { text: String ->
                selected = text
            }
            Row(
                horizontalArrangement = Arrangement.SpaceEvenly,
                modifier = Modifier.fillMaxWidth() // 补全修饰符保证平分宽度生效
            ) {
                buttonGroup.forEach { text ->
                    val isSelected = text == selected
                    Button(
                        // 移除enabled绑定,所有按钮全程保持可点击
                        onClick = { onSelectedChange(text) },
                        // 自定义选中/未选中样式,可按需调整
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = if (isSelected) MaterialTheme.colors.primary else MaterialTheme.colors.surface,
                            contentColor = if (isSelected) MaterialTheme.colors.onPrimary else MaterialTheme.colors.onSurface
                        ),
                        modifier = Modifier.padding(horizontal = 16.dp)
                    ) {
                        Text(
                            text = text,
                            style = MaterialTheme.typography.body1,
                            modifier = Modifier.padding(horizontal = 16.dp)
                        )
                    }
                }
            }
        }
        Surface() {
            MaterialButtonToggleGroup()
        }
    }
}

额外优化说明

  • 去掉了外层多余的Row和selectable修饰符,Button本身自带点击事件,不需要重复设置点击逻辑
  • 样式可根据你的设计需求自由调整,比如加边框、改圆角、修改选中态的文字样式都可以,只需要对应修改Button的修饰符和属性即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:06:03