2017-08-13 56 views
0

如何迭代一個視圖的子元素,並刪除所有具有開始標記的ImageView以一個特定的字符串? 所有例子我可以找到這個迭代器;使用標記刪除所有ImageView

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(即第二個項目)。

謝謝

+1

開始與最後一個孩子,和遞減下降到第一位。 –

回答

0

有幾個選項。

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); 
    } 
} 
相關問題