从视图中删除所有子视图

131

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

你可以通过以下代码实现从widget中删除所有子视图:
``` gridView.removeAllViews(); ```
这将从GridView中删除所有子视图,并使其为空。
4个回答

230

5
当在GridView上调用removeAllViews()方法时,实际上会抛出一个异常。根据文档,"当调用此方法时,不支持此操作并且会抛出UnsupportedOperationException异常。" - Moritz
该注释适用于ViewGroup派生的抽象基类。ViewGroup本身及其所有派生类都支持removeAllViews。 - Dale Wilson
如何获取 ViewGroup - Nimmagadda Gowtham
@NimmagaddaGowtham 大多数 XxxLayout 类(LinearLayout、RelativeLayout 等)都是 ViewGroup 的子类。如果您已经有其中之一,那么您已经拥有了一个 ViewGroup。 - GrandOpener

16
你可以使用此功能仅移除 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
因为原帖并没有询问如何删除不同类型的子视图,而是想要删除所有子视图,所以被踩了。 - protectedmember

6

试试这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接