Picasso Callback/Target没有回调(特别是第一次)

Picasso的Targets/Callback是弱引用,可能被GC回收,也可能没回收,所以回调变成了随机事件。

  DeferredRequestCreator(RequestCreator creator, ImageView target, Callback callback) {
    this.creator = creator;
    // 定义弱引用
    this.target = new WeakReference<ImageView>(target);
    this.callback = callback;

    ...
  }

  @Override public boolean onPreDraw() {
    ImageView target = this.target.get();
    if (target == null) {
      // 被回收 直接返回了
      return true;
    }
    ...
  }

解决办法,将Targets/Callback强引用,用完之后释放。来自stackoverflow

// 直接下载图片,需要在work thread
Picasso.with(context).load(url).get();

// Callback
ImageView profile = new ImageView(context);
Picasso.with(context).load(URL).into(profile, new Callback() {
    @Override
    public void onSuccess() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {//You will get your bitmap here

                Bitmap innerBitmap = ((BitmapDrawable) profile.getDrawable()).getBitmap();
            }
        }, 100);
    }

    @Override
    public void onError() {

    }
});

//or

// Target
final List<Target> targets = new ArrayList<Target>();
for (int i = 0; i < 3; i++) { 
    final int k=i;
    Target target = new Target() {

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {                         
            Log.i("load", "Ok " + k);   
            //use bitmap for add marker to map
            targets.remove(this);                
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            targets.remove(this);
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            Log.i("load", "first " + k);
        }
    }
    targets.add(target);
    Picasso.with(this)
        .load(ListA.get(i).getImage()) //image
        .resize(100, 100)
        .transform(new ImageTrans_CircleTransform())
        .into(target);  
}

Picasso Callback/Target没有回调(特别是第一次)》有1个想法

发表评论

电子邮件地址不会被公开。 必填项已用*标注