因此,我在布局中定义了一个ChipGroup
,我想在其中添加多个芯片。我为一般的Chip
创建了一个单独的实体,如下所示:
single_chip.xml
<com.google.android.material.chip.Chip
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/chip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkable="false"
android:textColor="@color/light_sapphire_blue"
android:theme="@style/Theme.MaterialComponents.Light"
app:chipBackgroundColor="@color/white"
app:closeIconTint="@color/bright_sky_blue"
app:closeIconVisible="true" />
所以在我的代码中,当我想在组中添加芯片时,我会这样:
View view = getLayoutInflater().inflate(R.layout.single_chip, null);
Chip chip = view.findViewById(R.id.chip);
for (Map.Entry<String, String> entry : selectedFilterMap.entrySet()) {
chip.setText(entry.getValue());
chipGroup.addView(chip);
chipGroup.setVisibility(View.VISIBLE);
}
但是在添加第一个芯片后(上面的代码被多次调用),我得到了这个错误:
“指定的孩子已经有一个父母。您必须调用removeView() 首先是孩子的父母。”
我应该在哪里打电话removeView
?我尝试将其添加到for
之前或之后的for
上,但是会出现相同的错误。
答案 0 :(得分:1)
您需要在for循环之前添加它。像这样
for (Map.Entry<String, String> entry : selectedFilterMap.entrySet()) {
View view = getLayoutInflater().inflate(R.layout.single_chip, null);
Chip chip = view.findViewById(R.id.chip);
chip.setText(entry.getValue());
chipGroup.addView(chip);
chipGroup.setVisibility(View.VISIBLE);
}