Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Last active March 16, 2022 02:17
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save JakeWharton/7189309 to your computer and use it in GitHub Desktop.
Save JakeWharton/7189309 to your computer and use it in GitHub Desktop.
A hierarchy change listener which recursively monitors and entire tree of views. Apache 2.
import android.view.View;
import android.view.ViewGroup;
/**
* A {@link ViewGroup.OnHierarchyChangeListener hierarchy change listener} which recursively
* monitors an entire tree of views.
*/
public final class HierarchyTreeChangeListener implements ViewGroup.OnHierarchyChangeListener {
/**
* Wrap a regular {@link ViewGroup.OnHierarchyChangeListener hierarchy change listener} with one
* that monitors an entire tree of views.
*/
public static HierarchyTreeChangeListener wrap(ViewGroup.OnHierarchyChangeListener delegate) {
return new HierarchyTreeChangeListener(delegate);
}
private final ViewGroup.OnHierarchyChangeListener delegate;
private HierarchyTreeChangeListener(ViewGroup.OnHierarchyChangeListener delegate) {
if (delegate == null) {
throw new NullPointerException("Delegate must not be null.");
}
this.delegate = delegate;
}
@Override public void onChildViewAdded(View parent, View child) {
delegate.onChildViewAdded(parent, child);
if (child instanceof ViewGroup) {
ViewGroup childGroup = (ViewGroup) child;
childGroup.setOnHierarchyChangeListener(this);
for (int i = 0; i < childGroup.getChildCount(); i++) {
onChildViewAdded(childGroup, childGroup.getChildAt(i));
}
}
}
@Override public void onChildViewRemoved(View parent, View child) {
if (child instanceof ViewGroup) {
ViewGroup childGroup = (ViewGroup) child;
for (int i = 0; i < childGroup.getChildCount(); i++) {
onChildViewRemoved(childGroup, childGroup.getChildAt(i));
}
childGroup.setOnHierarchyChangeListener(null);
}
delegate.onChildViewRemoved(parent, child);
}
}
@chewenkai
Copy link

Nice work

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