Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple way to add a predraw listener to a view
public abstract class PreDrawer<T extends View> {
// Private constructor prevent instantiation by the caller. Use addPredrawer() method instead.
private PreDrawer(final T view) {
// Adds the observer to the given view, then calls notifyPredraw() when clean up has been done ready
final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnPreDrawListener(this);
} else {
view.getViewTreeObserver().removeOnPreDrawListener(this);
}
notifyPreDraw(view);
return true;
}
});
}
// abstract final void method to force implementation
public abstract void notifyPreDraw(final T view);
// Takes a given view, adds a predraw listener to it, then calls the listener when ready
public static <T extends View> void addPreDrawer(T view, final OnPreDrawListener<T> listener) {
new PreDrawer<T>(view) {
@Override
public void notifyPreDraw(final T view) {
listener.onPreDraw(view);
}
};
}
// Interface to simplify callback. Essentially copied View.OnClickListener() code
public interface OnPreDrawListener<T> {
void onPreDraw(final T view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.