Android 无法将多个芯片添加到芯片组中

Android 无法将多个芯片添加到芯片组中,android,material-design,Android,Material Design,我正在尝试将芯片添加到芯片组而不是单线: val chip = Chip(this) chip.isCloseIconVisible = true for (i in 0..10) { chip.setText("Some text $i") chip_group.addView(chip as View) } 但我有一个例外: The specified child already has a parent. You must call

我正在尝试将芯片添加到芯片组而不是单线:

val chip = Chip(this)
    chip.isCloseIconVisible = true
    for (i in 0..10) {
        chip.setText("Some text $i")
        chip_group.addView(chip as View)
    }
但我有一个例外:

The specified child already has a parent. You must call removeView() on the child's parent first.

如何将chip标记为唯一的孩子?或者我该怎么办?

您需要为循环声明芯片内部

for (i in 0..10) {
    val chip = Chip(this)
    chip.isCloseIconVisible = true
    chip.setText("Some text $i")
    chip_group.addView(chip as View)
}

由于您将其声明为val,这意味着未更改它为val,因此会出现相同的子错误。

您不能将同一视图多次添加到父视图

请参阅:

它抛出上述异常

您多次尝试将同一芯片添加到父级

尝试修改代码,如

    for (i in 0..10) {
        val chip = Chip(this)
        chip.isCloseIconVisible = true
        chip.setText("Some text $i")
        chip_group.addView(chip as View)
    }

你是对的。但是为什么呢?我在循环中使用相同的上下文