Know which checkbox is clicked

Asked

Viewed 100 times

3

I have 20 static checkboxes, when I click on one of them I run a function through the onClick. This may be a stupid question, but how do I know exactly which of the 20 checkboxes was clicked? I already have one if that checks if any of the 20 checkboxes is clicked through the 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’ll have to make 20 cases?! Isn’t there a different way?

  • It depends.. What do you need to know which one was clicked on? What are you going to do with this information? if you access this within the function, this is the clicked checkbox.

1 answer

2


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

android:onClick="onCheckboxClicked"/>

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

public void onCheckboxClicked(View view) {

}

To view passed to the method is the Checkbox clicked.
Do the cast of View for Checkbox and use it however you want.

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
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.