22

I have a class called Question which contains a String array of tags. I'm trying to show every question in a Recyclerview using Kotlin and every tag in a new chip. These chips will be included inside a ChipGroup.

My question is:

How can I add every tag element of the array into a new Chip? I'm trying to do this but It's obviously not working.

if (tags != null) {
    for (tag in tags) {
        val chip = Chip(itemView.context)
    }
}
1
  • Is this your entire code so far? You're not adding the new Chip instances to a parent View anywhere. It's also half Kotlin and half Java.
    – zsmb13
    May 23, 2018 at 17:48

2 Answers 2

45

You can add Chips the same way as any other ViewGroup like so:

for (index in tags.indices) {
  val chip = Chip(chipGroup.context)
  chip.text= "Item ${tags[index]}"

  // necessary to get single selection working
  chip.isClickable = true
  chip.isCheckable = true
  chipGroup.addView(chip)
}

for singleSelection don't forget to add to your chipGroup:

chipGroup.isSingleSelection = true

or in xml

app:singleSelection="true"
2
  • 14
    @Choletski the question was asked in kotlin so it was answered in kotlin. The same thing can be applied for Java. It should be a very straightforward change
    – kandroidj
    Dec 3, 2018 at 13:16
  • @kandroidj How to get selected value of dynamic chips Dec 5, 2019 at 4:45
5

I always got the following error when trying to create a new Chip:

IllegalArgumentException: This component requires that you specify a valid android:textAppearance attribute

This could be fixed by instead inflating a custom R.layout.chip with the following line: android:textAppearance="@style/TextAppearance.MaterialComponents.Chip"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.