Skip to content

Instantly share code, notes, and snippets.

@kevinthecity
Last active August 29, 2015 14:00
Show Gist options
  • Save kevinthecity/11192121 to your computer and use it in GitHub Desktop.
Save kevinthecity/11192121 to your computer and use it in GitHub Desktop.
Recursively remove children from ViewGroups
public static void removeAllViews(final ViewGroup viewGroup) {
while (viewGroup.getChildCount() != 0) {
boolean childrenHaveChildren = false;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
final ViewGroup childViewGroup = (ViewGroup) child;
if (childViewGroup.getChildCount() != 0) {
removeAllViews(childViewGroup);
childrenHaveChildren = true;
}
}
}
if (!childrenHaveChildren) {
viewGroup.removeAllViews();
}
}
}
@kevinthecity
Copy link
Author

Simple recursive function for removing all views from a ViewGroup, including child views of child ViewGroups. Not the most efficient solution, but it gets the job done for most cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment