Fetch images with Callback in Picasso?

2019-01-18 05:17发布

问题:

I want to show a photo series with no gaps in-between the photos, where photos change in a regular interval. I realized Picasso initializes the ImageView before it starts downloading, and it always does that, no matter if I fetch() or not before calling into().

I fetch() to keep the gap between images small and also use .placeholder(R.color.black), but the gap is still visible, even when the image is loaded from memory.

My code looks like this

Picasso.with(getContext()).load(url).fetch();

then with a delay [which is currently fix and which I want to adjust dependent on network speed]

Picasso.with(getContext()).load(url).into(screenSurface);

I noticed that fetch() does not support any callback parameters and returns void, so it seems it's not possible for me to know when the cache is warmed.

Two questions:

  1. Can I get noticed when an image is cached?
  2. Is there maybe a different way to get rid of the breaks between the images and make them appear regularly.

[I know I could manually code this somehow, but if Picasso supports it, I'd like to use it.]

回答1:

Based on the source, it looks like fetch does nothing upon completion, including notifying any potential listeners. Unfortunately, FetchAction isn't a public class, so you can't override this functionality either.

You can workaround this problem by using a custom Target subclass, like this:

Picasso.with(getContext()).load(url).into(new Target() {
    @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        // cache is now warmed up
    }
    @Override public void onBitmapFailed(Drawable errorDrawable) { }
    @Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
});


回答2:

I know this is an older question but the fetch() command allows for callbacks such as fetch(Callback callback). This has an onSuccess() and onError() callback for the requested URI load.

See here for javadoc details



回答3:

The .into() method provides a second argument which is a callback to success and failure. You can use this to keep track of when an image has arrived.

Javadoc: http://square.github.io/picasso/javadoc/com/squareup/picasso/RequestCreator.html#into-android.widget.ImageView-com.squareup.picasso.Callback-

Have a look at this: How to implement my own disk cache with picasso library - Android? Jake Wharton himself has an answer there.