2011-11-05 83 views
74

如何从控件中删除所有子视图?例如,我有一个GridView,并且我动态地将许多其他LinearLayout充气到它中;后来在我的应用程序中,我正在寻找新的GridView并清除所有的子视图。我将如何做到这一点? TIA。从视图中删除所有子视图

回答

143
viewGroup.removeAllViews() 

适用于任何viewGroup。在你的情况下,它是GridView。

http://developer.android.com/reference/android/view/ViewGroup.html#removeAllViews()

+0

感谢您的帮助! –

+4

事实上,在GridView上调用removeAllViews()时会引发异常。从文档:“此方法不受支持,并在调用时引发UnsupportedOperationException。” – Moritz

+0

该注释适用于派生ViewGroup的抽象基类。 ViewGroup本身及其所有派生类都支持removeAllViews。 –

11

您可以使用此功能只删除某些类型的视图在的ViewGroup

private void clearImageView(ViewGroup v) { 
    boolean doBreak = false; 
    while (!doBreak) { 
     int childCount = v.getChildCount(); 
     int i; 
     for(i=0; i<childCount; i++) { 
      View currentChild = v.getChildAt(i); 
      // Change ImageView with your desired type view 
      if (currentChild instanceof ImageView) { 
       v.removeView(currentChild); 
       break; 
      } 
     } 

     if (i == childCount) { 
      doBreak = true; 
     } 
    } 
} 
+0

由于OP没有询问如何删除不同类型的子视图,因此进行了倒票。 OP想要删除所有的子视图。 – protectedmember

0
void removeAllChildViews(ViewGroup viewGroup) { 
    for (int i = 0; i < viewGroup.getChildCount(); i++) { 
     View child = viewGroup.getChildAt(i); 
     if (child instanceof ViewGroup) { 
      if (child instanceof AdapterView) { 
       viewGroup.removeView(child); 
       return; 
      } 
      removeAllChildViews(((ViewGroup) child)); 
     } else { 
      viewGroup.removeView(child); 
     } 
    } 
} 
0

试试这个

RelativeLayout relativeLayout = findViewById(R.id.realtive_layout_root); 
    relativeLayout.removeAllViews(); 

此代码工作我。