Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)     } } 
like image 509
ramon guardia Avatar asked May 23 '18 17:05

ramon guardia


People also ask

What are Android chips?

Chips are compact elements that represent an attribute, text, entity, or action. They allow users to enter information, select a choice, filter content, or trigger an action.

What is chip group in Android Studio?

A ChipGroup is used to hold multiple Chip s. By default, the chips are reflowed across multiple lines. Set the app:singleLine attribute to constrain the chips to a single horizontal line. If you do so, you'll usually want to wrap this ChipGroup in a HorizontalScrollView .


2 Answers

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" 
like image 135
kandroidj Avatar answered Sep 26 '22 15:09

kandroidj


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"

like image 33
Nicolai Weitkemper Avatar answered Sep 22 '22 15:09

Nicolai Weitkemper