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

Jetpack Compose LazyColumn单选/取消单选功能实现异常问题

问题原因

你现在的问题出在全局的isSelected状态——所有列表项都共用这个布尔值,只要它变成true,所有行都会显示勾选图标。而且点击逻辑里先把selectedIndex设为当前点击的index,紧接着判断selectedIndex == index,这时候肯定成立,会切换isSelected的状态,直接导致所有行同步显示/隐藏勾选。

修正代码
@Composable
fun LazyColumnWithSelection() {
    // 用-1表示初始无选中项,不需要单独的isSelected状态
    var selectedIndex by remember { mutableStateOf(-1) }

    val onItemClick = { index: Int ->
        // 点击已选中的项就取消选中,否则选中当前项
        selectedIndex = if (selectedIndex == index) -1 else index
    }

    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(100) { index ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onItemClick(index) }
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "Item $index", modifier = Modifier.padding(12.dp), color = Color.White)
                // 只在当前项的index等于selectedIndex时显示勾选图标
                if (selectedIndex == index) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = "Selected",
                        tint = Color.Green,
                        modifier = Modifier.size(20.dp)
                    )
                }
            }
        }
    }
}
关键改动说明
  • 移除了全局的isSelected变量,只用selectedIndex跟踪选中项:用-1表示没有任何项被选中,逻辑更简洁
  • 简化点击逻辑:点击项时直接判断,若为已选中项则取消选中(设为-1),否则选中当前项
  • 每个列表项单独判断自身index是否匹配selectedIndex,仅匹配时显示勾选图标,确保同一时间只有一个项处于选中状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 08:01:02