Для этого вы можете использовать ChipGroup и Chip (https://material.io/develop/android/components/chip/) и изменять цвет при выборе чипа
Для ChipGroup и добавлять Chip внутри в XML:
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipGroupOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.chip.Chip
android:id="@+id/chip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</com.google.android.material.chip.ChipGroup>
В коде добавьте чип в группу следующим образом:
ChipGroup chipGroup = view.findViewById(R.id.chipGroupOne);
Chip chip = new Chip(getContext());
chip.setId(id);
chip.setText("text");
chip.setCheckable(true);
chipGroup.addView(chip);
Чтобы изменить цвет, как вы хотите, вам нужно изменить атрибут стиля чипа с помощью собственного стиля, например
style.xml
<style name="CustomChip" parent="@style/Widget.MaterialComponents.Chip.Choice">
<item name="chipBackgroundColor">@color/chip_state</item>
<item name="android:textColor">@color/text_color_chip</item>
</style>
text_color_chip.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:color="@color/primaryColorCheck" />
<item android:state_checked="false"
android:color="@color/primaryColorUncheck" />
</selector>
chip_state.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorSecondaryLight" android:state_checked="true" />
<item android:color="@color/colorPrimaryDark" />
</selector>
И применить такой же стиль в XML с добавлением этого атрибута в chip
style="@style/CustomChip"
Если вы хотите применить стиль к программному чипу программно, вам нужно применить новый ChipDrawable, который содержит стиль к чипу, например:
chip.xml
<chip xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/CustomChip"
/>
ипримените так в коде
chip.setChipDrawable(ChipDrawable.createFromResource(getContext(), R.xml.chip));
Я надеюсь, что смогу помочь вам