Runs the given action in an View ViewTreeObserver OnPreDrawListener - Android User Interface

Android examples for User Interface:View

Description

Runs the given action in an View ViewTreeObserver OnPreDrawListener

Demo Code


//package com.java2s;

import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;

public class Main {
    /**//  w  ww .  j  a  v  a2s.  com
     * Runs the given action in an {@link OnPreDrawListener}
     *
     * @param view   The view from which to extract the {@link OnPreDrawListener}
     * @param action The action to perform
     */
    public static void onPreDraw(final View view, final Runnable action) {
        if (view != null && action != null) {
            final ViewTreeObserver vto = view.getViewTreeObserver();
            if (vto.isAlive()) {
                vto.addOnPreDrawListener(new OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        ViewTreeObserver vto = view.getViewTreeObserver();
                        if (vto.isAlive()) {
                            vto.removeOnPreDrawListener(this);
                        }

                        action.run();

                        return true;
                    }
                });
            }
        }
    }
}

Related Tutorials