I’m making a simple ‘tic tac toe’ game and so I have 9 buttons. These 9 buttons have the same
on click listener which I set in the layout “on click” property so that I don’t have to create 9 buttons in code just to set the listener.
My problem is that I have to remove all the listeners
from the buttons when a game is won or tied.
Is there a way to loop through all the buttons without actually having to create 9 button variables and setting each listener to null?
My code:
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";
}
}
You can use this function to traverse the view tree and remove all listeners: