Removing All Child Views from View
AndroidAndroid 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);
}
}
}