Change Chip Widget style programmatically not working – Android

You can’t use the constructor val chip = Chip(context, null, R.style.CustomChipChoice) because the 3rd parameter isn’t the style but the attribute in the theme as R.attr.chipStyle.
The Chip hasn’t a constructor with 4 parameters as other components because it extends AppCompatCheckbox which does not support a 4 parameter constructor.

However you can use something different.
1st option:

Just use a xml layout (single_chip_layout.xml) to define the single Chip with your favorite style:

<com.google.android.material.chip.Chip
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/CustomChipChoice"
    ...
/>

with

<style name="CustomChipChoice" parent="@style/Widget.MaterialComponents.Chip.Choice">
...
</style>

Then instead of val chip = Chip(context, null, R.style.CustomChipChoice) use:

val chip = layoutInflater.inflate(R.layout.single_chip_layout, chipGroup, false) as Chip

In java:

Chip chip =
          (Chip) getLayoutInflater().inflate(R.layout.single_chip_layout, chipGroup, false);

2nd option:

Another option is to use the setChipDrawable method to override the ChipDrawable inside the Chip:

  Chip chip = new Chip(this);
  ChipDrawable chipDrawable = ChipDrawable.createFromAttributes(this,
      null,
      0,
      R.style.Widget_MaterialComponents_Chip_Choice);
  chip.setChipDrawable(chipDrawable);

Leave a Comment