0

I'm trying to create a tic tac toe game for practice using simple buttons that change their text to x or o. Once a winner is found, all buttons should be reset to have the text "..." instead of x/o. It feels stupid to be doing this for each button but I can't figure out how to iterate over them. The buttons are named button1, button2, ..., and button9. Right now I'm using the same 3 lines of code for each button and just repeating that and that's not very DRY-friendly.

Tried to do a for loop and string concatenation (sort of like: findViewById(R.id."button"+i), but that obviously doesn't work hahah). I'm sure this is a stupid question but I've had this problem a couple of times now and I really wanna figure out how to so this better. [Image of the App][1]

 if(winnerFound){
            // print winner on screen and reset game
            resetGame();
        }
    }

    public void resetGame(){
        // set all buttons clickable again and set text to "..."
        // could be done in a for loop but idk how
        
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setText("...");
        button1.setEnabled(true);

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setText("...");
        button2.setEnabled(true);
        
        Button button3 = (Button) findViewById(R.id.button3);
        button3.setText("...");
        button3.setEnabled(true);

        Button button4 = (Button) findViewById(R.id.button4);
        button4.setText("...");
        button4.setEnabled(true);

// ... (9 buttons in total)'''


  [1]: https://i.stack.imgur.com/1ocbZ.jpg
Dr Mido
  • 2,414
  • 4
  • 32
  • 72
J_R
  • 23
  • 4
  • 1
    Does this answer your question? [Loop through all subviews of an Android view?](https://stackoverflow.com/questions/2597230/loop-through-all-subviews-of-an-android-view) – javdromero Oct 07 '22 at 13:49

1 Answers1

0

Simple solution based on your code: Create a member variable holding the list of your buttons List<Button> and iterate them setting the text to empty.

class MyActivity: Activity {
   private val buttonList: MuttableList<Button>
   private val button1: Button
   private val button2: Button

   fun onCreate(...) {
      button1 = findViewById(R.id.button_01)
      button2 = findViewById(R.id.button_02)

      buttonList.add(button1)
      buttonList.add(button2)
      ....
   }
}

More consideration about your code:

  1. You shouldn't use findViewById every time you want to use a button referente. It should be ideally only used once in your onCreate method of your activity(onViewCreated if it's a fragment) and set to a member variable .

Example

class MyActivity: Activity {
   private val button1: Button

   fun onCreate(...) {
      button1 = findViewById(R.id.button_01)
   }
}
Maicon Hellmann
  • 450
  • 3
  • 13