How to get when an ImageView is completely loaded in Android
Call loadBitmapFromView
in a such way:
mImage.post(new Runnable() {
@Override
public void run() {
loadBitmapFromView(mImage);
}
});
Runnable
provided to post()
method will be executed after view measuring and layouting, so getWidth()
and getHeight()
will return actual width and height.
What else can you do, is measuring View
manually, by invoking measure
, and then taking result from getMeasuredWidth()
and getMeasuredHeight()
. But I do not recommend this way.
There is actually another, more reliable way to do that by using ViewTreeObserver.OnPreDrawListener
. And here is an example:
mImage.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
try {
loadBitmapFromView(mImage);
// Note that returning "true" is important,
// since you don't want the drawing pass to be canceled
return true;
} finally {
// Remove listener as further notifications are not needed
mImage.getViewTreeObserver().removeOnPreDrawListener(this);
}
}
});
Using OnPreDrawListener
guarantees that View
was measured and layouted, while View#post(Runnable)
just executes your Runnable
when all Views are already most likely measured and layouted.