I have a custom viewgroup (that contains Picasso-loaded images) that can be reused in two places:
Here is my solution:
/**
* Loads the request into an imageview.
* If called from a background thread, the request will be performed synchronously.
* @param requestCreator A request creator
* @param imageView The target imageview
* @param callback a Picasso callback
*/
public static void into(RequestCreator requestCreator, ImageView imageView, Callback callback) {
boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
if (mainThread) {
requestCreator.into(imageView, callback);
} else {
try {
Bitmap bitmap = requestCreator.get();
imageView.setImageBitmap(bitmap);
if (callback != null) {
callback.onSuccess();
}
} catch (IOException e) {
if (callback != null) {
callback.onError();
}
}
}
}
Perfect answer by Jacob Tabak
Here is small addition that handles the case if you load image into Target
. I haven't found a way to get the origin of image to pass appropriate LoadedFrom
argument.
public static void into(RequestCreator requestCreator, Drawable placeHolder, Drawable errorDrawable, Target target) {
boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
if (mainThread) {
requestCreator.into(target);
} else {
try {
target.onBitmapFailed(placeHolder);
Bitmap bitmap = requestCreator.get();
target.onBitmapLoaded(bitmap, Picasso.LoadedFrom.MEMORY);
} catch (IOException e) {
target.onBitmapFailed(errorDrawable);
}
}
}