Skip to content

Instantly share code, notes, and snippets.

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() {
public boolean onPreDraw() {
if (viewTreeObserver.isAlive()) {
} else {
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) {
public void notifyPreDraw(final T 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