从所有按钮上删除单击侦听器?

1 android onclick listener

我正在做一个简单的'tic tac toe'游戏,所以我有9个按钮.这9个按钮具有相同的点击监听器,我在布局"on click"属性中设置,这样我就不必在代码中创建9个按钮来设置监听器.

我的问题是,当游戏获胜或并列时,我必须从按钮中删除所有听众.

有没有办法循环所有按钮而不必实际创建9个按钮变量并将每个侦听器设置为null?

我的代码:

public void onClick(View v) {
    Button b = (Button) v;
    Integer tag = Integer.parseInt((String) b.getTag());
    values[tag] = turnToPlay;
    b.setText(turnToPlay);
    b.setOnClickListener(null);
    playerTurn.setText("Player " + turnToPlay + " turn");

    if(isBoardFull()) {
        playerWon.setText("Tie Game!!");
        removeAllListeners()
    }

    if(turnToPlay.equalsIgnoreCase("X")) {
        turnToPlay = "O";
    }

    else {
        turnToPlay = "X";
    }    
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*ke4 5

您可以使用此函数遍历视图树并删除所有侦听器:

public void removeListeners() {
    View topView = getWindow().getDecorView();
    traverseTree(topView);
}

private void traverseTree(View view) {

    if(view instanceof ViewGroup) {
        ViewGroup group = (ViewGroup)view;
            for(int index = 0; index < group.
                getChildCount(); index++) {
                traverseTree(group.getChildAt(index));
            }
        } 

        else if (view instanceof Button) {
            Button button = (Button)view;
            button.setOnClickListener(null);
        }
    }
Run Code Online (Sandbox Code Playgroud)