Know which checkbox is clicked

3

I have 20 static checkboxes, clicking on one of them executes a function through onClick . But this is perhaps a stupid question but how do I know exactly which of the 20 checkboxes it was clicked on? I already have if that checks if any of the 20 checkboxes are clicked through isChecked()==true but it does not tell me if it was checkbox a, b, or c.

I saw this solution

switch (v.getId()) {

case R.id.Checkboxes_1 :
break;

case R.id.Checkboxes_2 :
break;

case R.id.Checkboxes_3 :
break;}

But then if I have 20 checkboxes, will I have to do 20 cases ?! Is not there a different way?

    
asked by anonymous 06.12.2016 / 18:50

1 answer

2

Use the android:onClick attribute of each CheckBox, in the xml, to assign the method that will handle click . Always use the same name for the method.

android:onClick="onCheckboxClicked"/>

In java declare a method with this name that receives a View and return void .

public void onCheckboxClicked(View view) {

}

The view passed to method is CheckBox clicked. Make cast from View to CheckBox and use it as you like.

public void onCheckboxClicked(View view) {

    CheckBox checkBoxClicked = (CheckBox)view;
    if(checkBoxClicked.isChecked()){

        //O CheckBox clicado foi seleccionado
        //aja de acordo
    }else{

        //O CheckBox clicado foi desseleccionado
        //aja de acordo
    }
}
    
06.12.2016 / 23:03