我有一个由类别名称组成的ChipGroup。当我离开片段并返回片段时,索引会增加。因此,第一个芯片从索引1变为11,从而导致索引超出范围异常。芯片数始终是正确的,因此我不确定索引如何增加。如果计数大于零,我试图清除视图。
// onViewCreated
@Override
public void onCheckedChanged(ChipGroup chipGroup, int i) {
Log.d(TAG, String.valueOf(i).concat(" : index of chip"));
binding.categorySearchbar.setText("");
if (i != -1) {
index = i;
if (categoriesList != null) {
if (i == 1) {
viewModel.searchByCategoryId(categoriesList.get(i - 1).getCategoryId());
binding.chipgroup.setSingleLine(true);
binding.selectedCategory.setText(categoriesList.get(i - 1).getName());
binding.selectedCategory.setVisibility(View.VISIBLE);
} else {
viewModel.searchByCategoryId(categoriesList.get(1).getSubcategory().get(i - 2).getCategoryId());
binding.chipgroup.setSingleLine(true);
binding.selectedCategory.setText(categoriesList.get(1).getSubcategory().get(i - 2).getName());
binding.selectedCategory.setVisibility(View.VISIBLE);
}
}
} else {
binding.chipgroup.setSingleLine(false);
adapter.clearList();
binding.selectedCategory.setVisibility(View.GONE);
}
}
});
//setting the chips
private void setCategories(List<Category> categories) {
if (getContext() != null) {
if (binding.chipgroup.getChildCount() > 0) {
binding.chipgroup.removeAllViewsInLayout();
binding.chipgroup.removeAllViews();
}
for (Category cat : categories) {
if (!cat.getName().equals("Shop by Category")) {
Chip chip = new Chip(getContext());
chip.setText(cat.getName());
chip.setCheckable(true);
chip.setClickable(true);
binding.chipgroup.addView(chip);
} else {
for (Subcategory sub : cat.getSubcategory()) {
Chip chip = new Chip(getContext());
chip.setText(sub.getName());
chip.setCheckable(true);
chip.setClickable(true);
binding.chipgroup.addView(chip);
}
}
}
}
Log.d(TAG, "setCategories : ".concat(String.valueOf(binding.chipgroup.getChildCount())));
}
答案 0 :(得分:0)
因此int i
中public void onCheckedChanged(ChipGroup chipGroup, int i)
的值实际上不是索引。而是一个id。我给人的印象是索引,但不是。我的总体解决方案是在声明每个芯片时为每个芯片设置一个点击监听器,并处理其中的逻辑。