2011-11-05 2 views
74

위젯에서 모든 하위 뷰를 어떻게 제거합니까? 예를 들어, GridView가 있고 다른 많은 LinearLayouts를 동적으로 팽창시킵니다. 나중에 내 응용 프로그램에서 그 GridView 신선한 시작하고 모든 자식 뷰를 지우려면 찾고 있어요. 어떻게하면 좋을까요? TIA.보기에서 모든 하위 뷰 제거

답변

143
viewGroup.removeAllViews() 

은 모든 viewGroup에 사용할 수 있습니다. 귀하의 경우 GridView입니다.

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

+0

도움을 주셔서 감사합니다! –

+4

실제로 removeAllViews()는 GridView에서 호출 될 때 예외를 throw합니다. 문서에서 : "이 메서드는 지원되지 않으며 호출 될 때 UnsupportedOperationException을 throw합니다." – Moritz

+0

이 주석은 ViewGroup이 파생 된 추상 기본 클래스에 적용됩니다. ViewGroup 자체 및 파생 된 모든 클래스는 removeAllViews를 지원합니다. –

11

당신은이 기능으로 뷰 그룹에서보기의 일부 유형을 제거 할 수 있습니다

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(); 

시도 나를.