Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 518
Vladimir Petrovski Avatar asked May 16 '19 08:05

Vladimir Petrovski


2 Answers

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

like image 167
Gabriele Mariotti Avatar answered Sep 30 '22 21:09

Gabriele Mariotti


I also came across this issue and I found this is working with the app:singleSelection="true"

    String selectedValue = "Male";
    genderBtnToggle.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
        @Override
        public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
            MaterialButton btn = genderBtnToggle.findViewById(checkedId);
            if (!isChecked && btn.getText().toString().equals(selectedValue)) {
                genderBtnToggle.check(checkedId);
            }

            if (isChecked) {
                selectedValue = btn.getText().toString();
            }
        }
    });
like image 29
Adnan Iqbal Avatar answered Sep 30 '22 21:09

Adnan Iqbal