Required single selection on MaterialButtonToggleGroup

I got this working with the following:

toggle_group.addOnButtonCheckedListener { group, checkedId, isChecked ->
    if (group.checkedButtonId == -1) group.check(checkedId)
}

If you have singleSelection enabled, the conditional will only evaluate to true when the user has clicked on the button which is already checked, making it so no button is checked. When this happens, we just need to check the button they unchecked.


You can define it in the layout using the app:selectionRequired attribute:

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

You can also use the method setSelectionRequired:

buttonGroup.setSelectionRequired(true);

Note: This requires a minimum of version 1.2.0-alpha03