Reputation: 2046
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.
Upvotes: 132
Views: 74939
Reputation: 1
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);
}
}
}
Upvotes: 0
Reputation: 8272
Try this
RelativeLayout relativeLayout = findViewById(R.id.realtive_layout_root);
relativeLayout.removeAllViews();
This code is working for me.
Upvotes: 7
Reputation: 1125
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;
}
}
}
Upvotes: 16
Reputation: 29121
viewGroup.removeAllViews()
works for any viewGroup. in your case it is GridView.
http://developer.android.com/reference/android/view/ViewGroup.html#removeAllViews()
Upvotes: 230