android – Know which checkbox clicked

Question:

I have 20 static checkboxes, when I click on one of them I execute a function through onClick . But this is perhaps a stupid question but how do I know exactly which of the 20 checkboxes was clicked? I for now have an if that checks if any of the 20 checkboxes are clicked through isChecked()==true but it doesn't 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 I will have to make 20 cases?! Isn't there a different way?

Answer:

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

android:onClick="onCheckboxClicked"/>

In java declare a method with that name that takes a View and returns void .

public void onCheckboxClicked(View view) {

}

The view passed to the method is the CheckBox clicked.
Cast View to CheckBox and use it however 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
    }
}
Scroll to Top