Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Material Button Toggle Group - Check None Selected

I am using MaterialButtonToggleGroup with single selection (only one button checked at a time). How to check if none of the buttons is checked?

        toggleGroup?.addOnButtonCheckedListener { group, checkedId, isChecked ->
        if (isChecked) {
            when (checkedId) {
                R.id.first_materialButton -> {
                    // do something when selected
                }

                R.id.second_materialButton -> {
                    // do something when selected
                }
            }
        }
    }
like image 584
Laura Avatar asked Apr 02 '20 08:04

Laura


2 Answers

The solution would be to get the checkedButtonId from the group on the else branch for isChecked, and if it the value is -1, then no button is selected.

toggleGroup?.addOnButtonCheckedListener { group, checkedId, isChecked ->
    if (isChecked) {
        when (checkedId) {
            R.id.first_materialButton -> {
                // do something when selected
            }

            R.id.second_materialButton -> {
                // do something when selected
            }
        }
    } else {
        if (group.checkedButtonId == View.NO_ID) {
           // do something when nothing selected
        }
    }
}
like image 175
Laura Avatar answered Oct 13 '22 00:10

Laura


If you need a listener check the @Laura's answer.

Otherwise you can use the getCheckedButtonIds() methods:

List<Integer> ids = materialButtonToggleGroup.getCheckedButtonIds();
if (ids.size() == 0){
  //Case unckecked
}

If you want to require a single selection you can use the app:singleSelection="true" attribute:

<com.google.android.material.button.MaterialButtonToggleGroup
    app:selectionRequired="true"
    app:singleSelection="true"
    ..>

This attribute requires a minimum of version 1.2.0-alpha03.

like image 21
Gabriele Mariotti Avatar answered Oct 13 '22 01:10

Gabriele Mariotti