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
}
}
}
}
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
}
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With