michael@0: /* michael@0: * Copyright (C) 2013 Square, Inc. michael@0: * michael@0: * Licensed under the Apache License, Version 2.0 (the "License"); michael@0: * you may not use this file except in compliance with the License. michael@0: * You may obtain a copy of the License at michael@0: * michael@0: * http://www.apache.org/licenses/LICENSE-2.0 michael@0: * michael@0: * Unless required by applicable law or agreed to in writing, software michael@0: * distributed under the License is distributed on an "AS IS" BASIS, michael@0: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. michael@0: * See the License for the specific language governing permissions and michael@0: * limitations under the License. michael@0: */ michael@0: package com.squareup.picasso; michael@0: michael@0: import android.view.ViewTreeObserver; michael@0: import android.widget.ImageView; michael@0: import java.lang.ref.WeakReference; michael@0: michael@0: class DeferredRequestCreator implements ViewTreeObserver.OnPreDrawListener { michael@0: michael@0: final RequestCreator creator; michael@0: final WeakReference target; michael@0: Callback callback; michael@0: michael@0: DeferredRequestCreator(RequestCreator creator, ImageView target, Callback callback) { michael@0: this.creator = creator; michael@0: this.target = new WeakReference(target); michael@0: this.callback = callback; michael@0: target.getViewTreeObserver().addOnPreDrawListener(this); michael@0: } michael@0: michael@0: @Override public boolean onPreDraw() { michael@0: ImageView target = this.target.get(); michael@0: if (target == null) { michael@0: return true; michael@0: } michael@0: ViewTreeObserver vto = target.getViewTreeObserver(); michael@0: if (!vto.isAlive()) { michael@0: return true; michael@0: } michael@0: michael@0: int width = target.getMeasuredWidth(); michael@0: int height = target.getMeasuredHeight(); michael@0: michael@0: if (width <= 0 || height <= 0) { michael@0: return true; michael@0: } michael@0: michael@0: vto.removeOnPreDrawListener(this); michael@0: michael@0: this.creator.unfit().resize(width, height).into(target, callback); michael@0: return true; michael@0: } michael@0: michael@0: void cancel() { michael@0: callback = null; michael@0: ImageView target = this.target.get(); michael@0: if (target == null) { michael@0: return; michael@0: } michael@0: ViewTreeObserver vto = target.getViewTreeObserver(); michael@0: if (!vto.isAlive()) { michael@0: return; michael@0: } michael@0: vto.removeOnPreDrawListener(this); michael@0: } michael@0: }