从视图中删除所有子视图


111

如何从窗口小部件中删除所有子视图?例如,我有一个GridView,并动态地将许多其他LinearLayouts填充到其中。稍后在我的应用程序中,我希望重新开始使用该GridView并清除其所有子视图。我该怎么做?TIA。

Answers:


199
viewGroup.removeAllViews()

适用于任何viewGroup。在您的情况下是GridView。

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


5
实际上,在GridView上调用removeAllViews()会引发异常。在Docs中:“不支持此方法,并且在调用时会引发UnsupportedOperationException。”
莫里茨

该注释适用于派生ViewGroup的抽象基类。ViewGroup本身及其所有派生类均支持removeAllViews。
戴尔·威尔逊

如何获得ViewGroup
Nimmagadda Gowtham

@NimmagaddaGowtham大多数XxxLayout类(LinearLayout,RelativeLayout等)是ViewGroup的子类。如果您有其中一个,则您已经有一个ViewGroup。
GrandOpener '16

15

您可以使用以下功能在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希望删除所有子视图。
保护会员

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);
        }
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.