Example usage for android.widget ImageView getViewTreeObserver

List of usage examples for android.widget ImageView getViewTreeObserver

Introduction

In this page you can find the example usage for android.widget ImageView getViewTreeObserver.

Prototype

public ViewTreeObserver getViewTreeObserver() 

Source Link

Document

Returns the ViewTreeObserver for this view's hierarchy.

Usage

From source file:uk.org.ngo.squeezer.util.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override {@link
 * ImageWorker#processBitmap(BitmapWorkerTaskParams)} to define the processing logic). A memory and disk cache
 * will be used if an {@link ImageCache} has been set using {@link
 * ImageWorker#setImageCache(ImageCache)}. If the image is found in the memory cache, it is set
 * immediately, otherwise an {@link AsyncTask} will be created to asynchronously load the
 * bitmap.//  ww  w .  ja  v a 2s . c om
 *
 * @param data The URL of the image to download
 * @param imageView The ImageView to bind the downloaded image to
 */
public void loadImage(final Object data, final ImageView imageView) {
    if (data == null) {
        return;
    }

    int width = imageView.getWidth();
    int height = imageView.getHeight();

    // If the dimensions aren't known yet then the view hasn't been measured. Get a
    // ViewTreeObserver and listen for the PreDraw message. Using a GlobalLayoutListener
    // does not work for views that are in the list but drawn off-screen, possibly due
    // to the convertview. See http://stackoverflow.com/a/14325365 for some discussion.
    // The solution there, of posting a runnable, does not appear to reliably work on
    // devices running (at least) API 7. An OnPreDrawListener appears to work, and will
    // be called after measurement is complete.
    if (width == 0 || height == 0) {
        // Store the URL in the imageView's tag, in case the URL assigned to is changed.
        imageView.setTag(data);

        imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                imageView.getViewTreeObserver().removeOnPreDrawListener(this);
                // If the imageView is still assigned to the URL then we can load in to it.
                if (data.equals(imageView.getTag())) {
                    loadImage(data, imageView);
                }
                return true;
            }
        });
        return;
    }

    loadImage(data, imageView, width, height);
}