2017-08-13 14 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の両方の変更になります。最初のアイテムと2番目のアイテム(最初のアイテムが実際に最初のアイテムである場合)を削除したい場合、posは1(つまり2番目のアイテム)として機能しません。

おかげ

+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); 
    } 
} 
関連する問題