H.Sunner
H.Sunner

Reputation: 39

Writing a for loop for nine buttons

I'm creating a simple naughts and crosses game in Android Studio for a university project, but I'm struggling to create a for loop for each of the nine buttons that loop through the arrays. How do would I go about this doing this?

Here is the code for the nine buttons to set the event listeners in the OnClickListener.

Button[] buttons = new Button[10];
        buttons[1] = (Button) findViewById(R.id.one);
        buttons[2] = (Button) findViewById(R.id.two);
        buttons[3] = (Button) findViewById(R.id.three);
        buttons[4] = (Button) findViewById(R.id.four);
        buttons[5] = (Button) findViewById(R.id.five);
        buttons[6] = (Button) findViewById(R.id.six);
        buttons[7] = (Button) findViewById(R.id.seven);
        buttons[8] = (Button) findViewById(R.id.eight);
        buttons[9] = (Button) findViewById(R.id.nine);

Upvotes: 2

Views: 92

Answers (1)

Francesc
Francesc

Reputation: 29260

You can have a single click listener for all buttons and then use a switch statement on the view id to determine which button was clicked. And you should start your array at 0, not 1.

private final View.OnClickListener mListener = new View.OnClickListener() {
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.one:
                // do stuff;
                break;
            case R.id.two:
                // do stuff;
                break;
            case R.id.three:
                // do stuff;
                break;
            case R.id.four:
                // do stuff;
                break;
            // add more
        }
    }
}

Then simply set this listener to your buttons

for (int i = 0; i < 9; ++i) {
    buttons[i].setOnClickListener(mListener);
}

Upvotes: 2

Related Questions