从视图中删除所有子视图

Nic*_*her 103 android

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

Yas*_*mar 188

viewGroup.removeAllViews()
Run Code Online (Sandbox Code Playgroud)

适用于任何viewGroup.在你的情况下,它是GridView.

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

  • 实际上removeAllViews()在GridView上调用时会抛出异常.来自Docs:"不支持此方法,并在调用时抛出UnsupportedOperationException." (5认同)

小智 13

您可以使用此功能仅删除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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Gow*_*n M 6

尝试这个

RelativeLayout  relativeLayout = findViewById(R.id.realtive_layout_root);
    relativeLayout.removeAllViews();
Run Code Online (Sandbox Code Playgroud)

这段代码对我有用。