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

Jetpack Compose切换按钮持续触发导致搜索栏UI故障

问题根因
  • 点击「Search Movies」后界面闪烁:isExpanded = !isExpanded被直接写在Composable的重组流程中,只要当前选中项为「Search Movies」,每次组件重组都会翻转isExpanded的值,进而触发新一轮重组,形成无限循环,最终表现为界面反复闪烁。
  • 切换到「Popular Movies」后搜索框不隐藏:代码仅在选中「Search Movies」时修改isExpanded取值,切换到其他选项时未对isExpanded做重置,因此搜索框不会隐藏。
修复方案

你需求的搜索框显隐逻辑完全可以通过selectedOption的取值直接判断,无需额外维护isExpanded状态变量,删掉冗余的状态即可解决两类异常。

修复后完整代码
@Composable
fun MaterialButtonToggleGroup() {
    val options = listOf(
        "Popular Movies",
        "Search Movies"
    )
    var selectedOption by remember {
        mutableStateOf("")
    }
    val onSelectionChange = { text: String ->
        selectedOption = text
    }
    Column() {
        Row(
            horizontalArrangement = Arrangement.SpaceEvenly,
            modifier = Modifier.fillMaxWidth(),
        ) {
            options.forEach { text ->
                Row(
                    modifier = Modifier
                        .padding(
                            vertical = 8.dp,
                        ),
                ) {
                    Text(
                        text = text,
                        style = typography.body1.merge(),
                        color = Color.White,
                        modifier = Modifier
                            .clip(
                                shape = RoundedCornerShape(
                                    size = 12.dp,
                                ),
                            )
                            .clickable {
                                onSelectionChange(text)
                            }
                            .background(
                                if (text == selectedOption) {
                                    Color.Magenta
                                } else {
                                    Color.Gray
                                }
                            )
                            .padding(
                                vertical = 12.dp,
                                horizontal = 16.dp,
                            ),
                    )
                }
            }
        }
        // 直接通过选中项判断搜索框是否展示
        if (selectedOption == "Search Movies") {
            var text by remember { mutableStateOf("") }
            OutlinedTextField(
                value = text,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(all = 3.dp),
                onValueChange = { text = it },
                label = { Text("Enter Movie Info") }
            )
        }
    }
    (activity as MainActivity?)?.viewSelection(selectedOption)
}

Surface {
    MaterialButtonToggleGroup()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:06:03