How to detect a click on an array of buttons in Android Studio

1

Look, I have an array of buttons that I obviously created in the "Java Code", I implemented the class of View.OnClickListener and within the onClick method (View view) I have the following:

public void onClick(View view){ 
          for (int x = 0; x < btnMatriz.length; x++) {
                for (int i = 0; i < btnMatriz[x].length; i++) {
                    switch (view.getId()) {
                            case /** */: //Mi problema es aqui, no se como obtener el id del boton al que le di click, normalmente va R.id.idDelBoton, pero en este caso la matriz de botones no se ubican en dentro del activity_main, sino que dentro del "Codigo de Java" incluso he intentado con case btnMatriz[x][i].getId() y masbien me tira un error

                              break;


                    }
                }
            }}

I would like that you could help me, how to get the id of the element, at least I would like to know if I am doing it right.

    
asked by Alexis Rodriguez 09.03.2017 в 05:08
source

1 answer

2

I guess after you generate your button matrix, you put them somewhere on the UI. if so, and if you created the buttons programmatically, you do not need to get their ID to give them an event like onClick.

The Id of an element serves to identify it when it was created through a layout, as you created it programmatically, you have the direct reference to the buttons, that is why you do not need it.

you can do the following.

for (int x = 0; x < btnMatriz.length; x++) {
   for (int i = 0; i < btnMatriz[x].length; i++) {
             btnMatriz[x][i].setOnClickListener(new OnClickListener (){
                   public void onClick(View view){ 
                         //haces lo que necesites
                   }  
              });   
   }  
}

This you can do, within your onCreate method or where you need them to be assigned.

    
answered by 09.03.2017 / 05:37
source