Home » Android » android – Removing All Child Views from View

android – Removing All Child Views from View

Posted by: admin March 11, 2020 Leave a comment

Questions:

How would I remove all child views from a widget? For example, I have a GridView and I dynamically inflate many other LinearLayouts into it; later in my application I am looking to start fresh with that GridView and clear all of its child Views. How would I do this? TIA.

How to&Answers:
viewGroup.removeAllViews()

works for any viewGroup. in your case it is GridView.

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

Answer:

You can remove only some types of view in a ViewGroup with this function :

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

Answer:

Try this

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

This code is working for me.

Answer:

Try this

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