Ad

Required Single Selection On MaterialButtonToggleGroup

Is there an option to make the MaterialButtonToggleGroup have a required selected button when using app:singleSelection="true"?

When clicking to a different button works fine (all other buttons are deselected), but when you click the same (already selected) button it deselects it itself and I want to remain selected.

My example:

 <com.google.android.material.button.MaterialButtonToggleGroup
      android:layout_width="wrap"
      android:layout_height="wrap_content"
      app:singleSelection="true">

      <com.google.android.material.button.MaterialButton
        android:id="@+id/filterA"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"/>

      <com.google.android.material.button.MaterialButton
        android:id="@+id/filterB"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="B"/>

      <com.google.android.material.button.MaterialButton
        android:id="@+id/filterC"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="C"/>

    </com.google.android.material.button.MaterialButtonToggleGroup>
Ad

Answer

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

Ad
source: stackoverflow.com
Ad