Android Material Button Toggle Group - Check None Selected
A

2

7

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
                }
            }
        }
    }
Antrim answered 2/4, 2020 at 8:6 Comment(0)
A
15

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
        }
    }
}
Antrim answered 2/4, 2020 at 8:6 Comment(0)
H
7

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.

Hutt answered 12/6, 2020 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.