如何检查 GridLayout 中的所有 ImageView 是否不为空?

How To Check if all ImageView inside GridLayout is not Empty?

我正在尝试使用 Android Studio 制作一个井字游戏。我已经编写了一段代码来设置有人获胜时按钮的可见性(并且有效)。我还希望游戏在棋盘已满但无人获胜(平局)时显示“再次玩”按钮。我该怎么做。

这是我要编写的代码:

public boolean checkGameState () {
    boolean isBoardFull = false;
    androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
    for (int i = 0; i < gridLayout.getChildCount(); i++) {
        ImageView reset = (ImageView) gridLayout.getChildAt(i);
        if(reset.getDrawable() != null) {
            isBoardFull = true;
        }
    }
    return isBoardFull;
}

这是游戏的截图:

如图所示,即使游戏尚未结束,“再次玩”按钮仍然可见。该按钮将显示某人是赢还是平(棋盘已满)。

我认为您应该在迭代 gridLayout 子项之前初始化一个变量 isEveryChildChecked = true。 在迭代子项时,如果未选中网格,请设置字段 isEveryChildChecked = false.

然后迭代后,检查字段isEveryChildChecked,如果为true,则可以显示play again 否则什么都不做或隐藏Play again 按钮。

您的条件存在轻微错误,因为一旦它发现可绘制,它就会标记为 isBoardFulltrue,这是错误的,因为所有 child 还没有被检查所以标记isBoardFull 因为 true 在这个阶段是错误的。

您可以按照以下方式进行操作:

public boolean checkGameState () {
    boolean isBoardFull = true; // first mark it as full
    androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
    for (int i = 0; i < gridLayout.getChildCount(); i++) {
        ImageView reset = (ImageView) gridLayout.getChildAt(i);
        if(reset.getDrawable() == null) {
            isBoardFull = false; // if drawable not found that means it's not full
        }
    }
    return isBoardFull;
}

所以现在首先它会将板标记为已满,但是一旦发现任何可绘制对象为空,它就会将板标记为空。