Change Chip Widget Style Programmatically Not Working - Android

Cannot add text color state list to Material Chip

The issue is here:

val chip = Chip(context, null, R.style.Widget_MaterialComponents_Chip_Choice)

In this way you aren't using the Widget.MaterialComponents.Chip.Choice style since you can't use the constructor val chip = Chip(context, null, R.style.xxxx) to assign a style because the 3rd parameter isn't the style but the attribute in the theme as R.attr.chipStyle.

For more details to change the Chip style programmatically check also this answer.

In your code you are using the default style for a Chip the Widget.MaterialComponents.Chip.Action which provides:

<item name="android:checkable">false</item>

It explains why your Chip is not checkable.

The method chip.setTextColor is correct and works with a selector (but use the selector as described by Ben.P in the other answer).

As you pointed out if you use it in the layout.xml it works since in this case the style declared in the layout is correct (Widget.MaterialComponents.Chip.Choice).

Is there a way to stay on the same Chip when I press it?

In other words, is there a property that keeps the checked check in its state even if it is still

selected?

Use Chip Choice then add the chips inside ChipGroup.

Add this line to your ChipGroup

<com.google.android.material.chip.ChipGroup
app:singleSelection="true"
app:selectionRequired="true"
app:checkedChip="@id/..."
..>

Then in your Chip

<android.support.design.chip.Chip
android:id="@+id/chip1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkable="true"
android:checked="true"
app:chipBackgroundColor="@color/bg_chip_state_list"
app:chipText="Test1" />

<android.support.design.chip.Chip
android:id="@+id/chip2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkable="true"
app:chipBackgroundColor="@color/bg_chip_state_list"
app:chipText="Test2" />

The key is the ChipGroup that has required selection



Related Topics



Leave a reply



Submit