0

I have a 2d array of buttons set up for a tic tac toe game.

their IDs are formatted as follows (relative to their coordinated on the board:

button00, button01, button02, button10...etc

Im trying to set up my construction for their view to happen dynamically without having to verbosely go through and address everyone:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        for(int x = 0; x< this.boardButtons.length; x++){
            for(int y = 0; y< this.boardButtons[x].length; y++){
                try {
                    Button button = findViewById(R.id.class.getMethod("button")); // <- reflective code is HERE
                } catch(Exception e){
                    e.printStackTrace();
                }

                this.boardButtons[x][y].setOnClickListener(new View.OnClickListener(){
                    public void onClick(View view){
                        Button clickedB = (Button) view;

                        clickedB.setText(zeroTurn ? R.string.t_o:R.string.t_x);
                        clickedB.setEnabled(false);
                        zeroTurn = !zeroTurn;
                    }
                });
            }
        }

So ideally I would construct the contents of the try block as follows:

Button button = findViewByID(R.id.button[x][y]); //etc

Through some research I discovered I could do something similar using reflections however the IDE keeps throwing an error when I try to do so:

findViewByID(int) in AppCompatActivity cannot be applied  to java.lang.reflect.Method

Can someone please elaborate on the proper implementation of what I'm trying to do

Adrian Coutsoftides
  • 1,203
  • 1
  • 16
  • 38

0 Answers0