使用标记删除所有图像视图



如何遍历视图的子级并删除所有带有以特定字符串开头的标记的 ImageViews? 我可以找到这个迭代器的所有示例;

for (int pos = 0; pos < mat.getChildCount(); pos++)
{
Object tag = mat.getChildAt(pos).getTag();
if (tag != null)
{
String s = tag.toString();
if (s.startsWith("Z"))
{
mat.removeView(mat.getChildAt(pos));
}
}
}

执行测试,然后删除对象。 问题是"pos"和getChildCount在整个过程中都会发生变化。如果我想删除第一项,然后删除第二项(第一次删除后实际上是第一项(,它将不起作用,因为 pos 现在是 1(即第 2 项(。

谢谢

有几个选项。

for (int pos = 0; pos < mat.getChildCount();) {
if (remove) {
mat.removeViewAt(pos);
continue;
}
// only increment if the element wasn't removed
pos++;
}
for (int pos = 0; pos < mat.getChildCount(); pos++) {
if (remove) {
mat.removeViewAt(pos);
// balance out the next increment
pos--;
}
}
// don't remove views until after iteration
List<View> removeViews = new ArrayList<>();
for (int pos = 0; pos < mat.getChildCount(); pos++) {
if (remove) {
removeViews.add(mat.getChildAt(pos));
}
}
for (View view : removeViews) {
mat.removeView(view);
}
// count in reverse
for (int pos = mat.getChildCount() - 1; pos >= 0; pos--) {
if (remove) {
mat.removeViewAt(pos);
}
}

最新更新