2011-11-05 51 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(); 

此代碼工作我。