2

In my xml layout I have a chip group with a filter chips.

<android.support.design.chip.ChipGroup
    android:id="@+id/chipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.chip.Chip
        style="@style/myStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    .....

</android.support.design.chip.ChipGroup>

As there are a lot of filters it's seems to be reasonable to add them in code. The problem is that I need to apply style attribute to every chip.

I tried:

val chip = Chip(ContextThemeWrapper(context, R.style.myStyle))
binding.chipGroup.addView(chip)

no effect

val chip = Chip(context, null, R.style.myStyle)
binding.chipGroup.addView(chip)

no effect

I created layout/filter_chip.xml and put there a chip template

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.chip.Chip 
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/myStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

and I create it in code like this

val chip = inflater.inflate(R.layout.filter_chip, binding.chipGroup, false) as Chip   
binding.chipGroup.addView(chip)

It works and style is applied. But I'm asking myself if it's really the simplest way to achieve it. Do you know the better one?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Vitalii
  • 10,091
  • 18
  • 83
  • 151

1 Answers1

-1

I think you can use ContextThemeWrapper by creating the ContextThemeWrapper with the style you want then passing the themed context to the constructor of the chip.

Mohamed Abdalkader
  • 469
  • 1
  • 4
  • 7