Search code examples
androidmaterial-componentsmaterial-components-androidandroid-chips

Avoid Chip Group to get unchecked


I have this following Chip Group and when I tap on a Chip that is already checked, it gets unchecked, but I have to always have a checked chip. The behavior is similar to the Radio Group.

<com.google.android.material.chip.ChipGroup
        android:id="@+id/chip_group_filter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:checkedChip="@id/chip_1"
        app:singleSelection="true">

        <com.google.android.material.chip.Chip
            android:id="@+id/chip_1"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/chip1"
            app:chipBackgroundColor="@color/chip_color" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chip_2"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/chip2"
            app:chipBackgroundColor="@color/chip_color" />

    </com.google.android.material.chip.ChipGroup>

Solution

  • You can require a selected chip with the app:selectionRequired attribute.
    Something like:

     <com.google.android.material.chip.ChipGroup
        android:id="@+id/chip_group_filter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:checkedChip="@id/chip_1"
        app:selectionRequired="true"
        app:singleSelection="true">
    

    Just a note: app:checkedChip or an initial selection is not required. If it is not set it works in any case without a selection.

    Note: this requires a minimum of version 1.2.0