보기에서 모든 하위보기 제거


111

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

답변:


199
viewGroup.removeAllViews()

모든 viewGroup에서 작동합니다. 귀하의 경우에는 GridView입니다.

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


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

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

얻는 방법 ViewGroup?
Nimmagadda Gowtham 2015

@NimmagaddaGowtham 대부분의 XxxLayout 클래스 (LinearLayout, RelativeLayout 등)는 ViewGroup의 자식 클래스입니다. 그중 하나가 있으면 이미 ViewGroup이있는 것입니다.
GrandOpener

14

다음 함수 를 사용하여 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;
        }
    }
}

1
OP가 다른 유형의 하위 뷰를 제거하는 방법을 묻지 않았기 때문에 반대 투표했습니다. OP는 모든 자식 뷰를 제거하려고했습니다.
protectedmember

3

이 시도

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

이 코드는 저에게 효과적입니다.


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);
        }
    }
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.