Removing All Child Views from View

Android

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

viewGroup.removeAllViews()

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

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

Solution 2 - Android

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

Solution 3 - Android

Try this

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

This code is working for me.

Solution 4 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick BetcherView Question on Stackoverflow
Solution 1 - AndroidYashwanth KumarView Answer on Stackoverflow
Solution 2 - AndroidTienLuongView Answer on Stackoverflow
Solution 3 - AndroidGowthaman MView Answer on Stackoverflow
Solution 4 - Androidkot32goView Answer on Stackoverflow