Munesawagi
Munesawagi

Reputation: 293

Determine if checkboxes are selected when button is pressed

I am building an Android app, and was wondering how to make a Java method that goes through all the checkboxes in a certain activity to see if any of them are checked.

I don't have any code currently, as I really do not know how to approach this.

Any pointers?

Upvotes: 2

Views: 82

Answers (1)

Arman P.
Arman P.

Reputation: 4394

When the button is clicked get the parent view group (assuming everything in your layout is in one viewgroup) and iterate through them. Check if any of them is checkbox and do what you need.

public void onButtonClicked(View view) {
    ViewGroup viewGroup = (ViewGroup) view.getParent();

    for (int i=0; i<viewGroup.getChildCount(); i++) {
        if (viewGroup.getChildAt(i) instanceof CheckBox) {
            if ((CheckBox) viewGroup.getChildAt(i).isChecked()) {
                // do something here
            }
        }
    }
}

Upvotes: 1

Related Questions