How can I add the new android chips dynamically in Android?

ramon guardia picture ramon guardia · May 23, 2018 · Viewed 16.9k times · Source

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)
    }
}

Thank you all!

Answer

kandroidj picture kandroidj · Jun 12, 2018

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"

Good Luck and Happy Coding!