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

Jetpack Compose制作3x3井字棋网格仅显示最后一行问题

问题解决:Jetpack Compose井字棋仅显示最后一行

问题原因

你的代码中,Surface 内部直接循环生成 Row,但没有用垂直布局容器(比如 Column)包裹这些行,导致三个 Row 重叠在一起,最终只能看到最后一行。另外,用 mutableMapOf 存储游戏状态会导致遍历顺序不稳定,可能打乱行的排列。

修改后的代码

enum class SquareStateValues {
    None,
    Cross,
    Nought
}

data class SquareState(val value: SquareStateValues = SquareStateValues.None)

// 改用List保证行顺序稳定
val gameState = listOf(
    Triple(SquareState(), SquareState(), SquareState()),
    Triple(SquareState(), SquareState(), SquareState()),
    Triple(SquareState(), SquareState(), SquareState())
)

@Composable
fun GameBoard() {
    Surface(modifier = Modifier.fillMaxSize()) {
        // 用Column垂直排列所有行
        Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
            gameState.forEachIndexed { rowIndex, row ->
                Row {
                    row.toList().forEachIndexed { colIndex, item ->
                        Button(
                            onClick = {},
                            modifier = Modifier.padding(8.dp).background(Color.Red)
                        ) {
                            Text("${rowIndex+1}:$colIndex")
                        }
                    }
                }
            }
        }
    }
}

关键修改点

  • 新增 Column 容器包裹所有 Row,让三行垂直有序排列。
  • 将 gameState 从 mutableMapOf 改为 List,确保遍历顺序固定,不会打乱行的顺序。
  • 移除每个按钮外层多余的 Column,简化布局层级,避免不必要的嵌套。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:10:11