You need to enable JavaScript to run this app. Android Studio Java开发:用控件ID正确填充5x5井字棋按钮二维数组的方法
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio Java开发:用控件ID正确填充5x5井字棋按钮二维数组的方法

现有代码的核心问题
  • 内层循环判断条件写错:遍历y坐标的循环,条件误写为x < 5而非y < 5,会导致内层循环无限运行,直接触发运行崩溃
  • 语法不完整:两层for循环都缺少闭合右大括号,本身无法通过编译
  • 执行时机问题:必须要在setContentView()加载完成布局之后,再调用这段初始化逻辑,否则findViewById会返回空控件
修正后的可运行实现

基于你已经定义好的按钮ID规则,直接修正原有循环逻辑即可正常运行:

// 先定义二维按钮数组
private Button[][] gameArray = new Button[5][5];

// 该方法需要在setContentView()执行完成后调用
private void initGameButtons() {
    for (int x = 0; x < 5; x++) {
        // 修正内层循环的判断条件为y轴边界校验
        for (int y = 0; y < 5; y++) {
            String gameButtonId = "buttons" + x + y;
            int gameID = getResources().getIdentifier(gameButtonId, "id", getPackageName());
            gameArray[x][y] = findViewById(gameID);
            // 增加空判断避免控件匹配失败时直接空指针崩溃
            if (gameArray[x][y] != null) {
                gameArray[x][y].setOnClickListener(this);
            }
        }
    }
}
更高效的可选优化方案

如果担心getIdentifier的反射性能损耗,或者怕编译开启资源混淆后ID名称被修改导致找不到控件,可以直接预定义所有按钮ID数组,遍历赋值:

// 按行列顺序直接绑定布局中的按钮ID,编译期就会完成ID合法性校验
private final int[][] buttonIds = {
        {R.id.buttons00, R.id.buttons01, R.id.buttons02, R.id.buttons03, R.id.buttons04},
        {R.id.buttons10, R.id.buttons11, R.id.buttons12, R.id.buttons13, R.id.buttons14},
        {R.id.buttons20, R.id.buttons21, R.id.buttons22, R.id.buttons23, R.id.buttons24},
        {R.id.buttons30, R.id.buttons31, R.id.buttons32, R.id.buttons33, R.id.buttons34},
        {R.id.buttons40, R.id.buttons41, R.id.buttons42, R.id.buttons43, R.id.buttons44}
};

private void initGameButtons() {
    for (int x = 0; x < 5; x++) {
        for (int y = 0; y < 5; y++) {
            gameArray[x][y] = findViewById(buttonIds[x][y]);
            gameArray[x][y].setOnClickListener(this);
        }
    }
}

这种方式不依赖资源名称匹配,运行效率更高,也不会被混淆规则影响。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 19:15:05