Picasso first run not call onBitmapLoaded in for loop

风流意气都作罢 提交于 2019-11-29 07:25:00

A common issue with using Picasso's Targets is that people don't keep strong references to them. This results in the targets being randomly working, because sometimes they get collected by the GC before being finished, and sometimes they live long enough to get the callback called.

What you have to do is to store those callbacks somewhere until they are finished. Here's an example:

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("Targets", "Loaded: " + k);   
            targets.remove(this);                
        }

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

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            Log.i("Targets", "Preparing: " + k);
        }
    }
    targets.add(target);
    Picasso.with(this)
        .load(ListA.get(i).getImage()) // Start loading the current target
        .resize(100, 100)
        .into(target);  
}

To make sure the list does not get GC'd too, make targets a global variable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!