Dynamically create Choice Chip in android

kinjal patel picture kinjal patel · Mar 26, 2019 · Viewed 9.5k times · Source

I am using Material Components for creating the Choice chip. I have followed https://material.io/develop/android/components/chip/ document. There is enough stuff for creating a chip in XML but not get an idea of how to create choice chip programmatically.

I have used following code to creating chip dynamically but it creates action chip by default.

val chip = Chip(activity)
chip.text = ("Chip 1")
chipGpRow.addView(chip)

Answer

Gabriele Mariotti picture Gabriele Mariotti · Oct 5, 2019

Check the Mike comment.

Otherwise you can define a simple layout (layout_chip_choice.xml) with the Chip and the style:

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

Then use in your code:

val chip = inflater.inflate(R.layout.layout_chip_choice, chipGpRow, false) as Chip  
chip.text = ("Chip 1")
chipGpRow.addView(chip)