【问题标题】:How To Check if all ImageView inside GridLayout is not Empty?如何检查 GridLayout 中的所有 ImageView 是否不为空?
【发布时间】:2022-01-21 04:01:33
【问题描述】:

我正在尝试使用 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;
}

这是游戏的截图:

正如您在图片中看到的那样,即使游戏尚未结束,“再玩一次”按钮仍然可见。该按钮将显示某人是赢还是平(棋盘已满)。

【问题讨论】:

    标签: java android android-layout


    【解决方案1】:

    您的条件有一点点错误,一旦发现可绘制,它将标记为isBoardFulltrue,这是错误的,因为尚未检查所有孩子,因此在此阶段将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;
    }
    

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

    【讨论】:

      【解决方案2】:

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

      然后在迭代后,检查字段isEveryChildChecked,如果为true,则可以显示再次播放,否则什么也不做或隐藏再次播放按钮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-22
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 2014-06-05
        • 1970-01-01
        • 2015-01-11
        相关资源
        最近更新 更多