Using a global layout listener on the view and runs the runnable when the view have received it's dimensions. - Android User Interface

Android examples for User Interface:Layout

Description

Using a global layout listener on the view and runs the runnable when the view have received it's dimensions.

Demo Code


//package com.java2s;

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

public class Main {
    /**//ww  w  . ja va 2  s.co m
     * Using a global layout listener on the view and runs the runnable when the view have received it's
     * dimensions. If the view already have dimensions, the runnable is run directly.
     *
     * @param view     View to observe.
     * @param runnable Runnable to run.
     */
    public static void runOnLayout(final View view, final Runnable runnable) {
        if (view.getWidth() == 0 || view.getHeight() == 0) {
            view.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            runnable.run();
                            view.getViewTreeObserver()
                                    .removeOnGlobalLayoutListener(this);
                        }
                    });
        } else {
            runnable.run();
        }
    }
}

Related Tutorials