ViewPager中的毕加索图像加载器:根据先到先得

时间:2015-12-09 11:47:37

标签: android android-viewpager picasso

我使用Picasso作为我的图像加载器库。我有一个ViewPager,用ImageViews显示一些片段。应从网络中提取要在图像视图中显示的图像。我的问题是在ViewPager中我只需要显示成功获取的图像(片段)。有可能吗?

1 个答案:

答案 0 :(得分:0)

我自己找到了。我在这里发帖是因为它可能会帮助一些面临类似情况的人。

我的ViewPagerAdapter如下:

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.drawable.Drawable;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;

    import com.squareup.picasso.Picasso;
    import com.squareup.picasso.Target;

    import java.util.ArrayList;
    import java.util.List;

    //ImageFragment is a normal fragment containing a ImageView
    import *****.ImageFragment;

/**
 * Created by sanifss on 07/12/15.
 */
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    private final String[] urls;
    private final Context context;
    private List<String> urlList;
    private final boolean zoomEnabled;
    private List<MyTarget> targets;

    public ScreenSlidePagerAdapter(Context context, FragmentManager fm, String[] urls, boolean zoomEnabled) {
        super(fm);
        this.urls = urls;
        this.context = context;
        this.zoomEnabled = zoomEnabled;
        urlList = new ArrayList<>();

        targets = new ArrayList<>();
        fetchImages();//images are first loaded and then added to the adapter in FCFS.
    }

    private void fetchImages() {
        for (String url : urls) {
            MyTarget target = new MyTarget(url);
            targets.add(target);//needed otherwise target object will get garbage collected
            Picasso.with(context).load(url).into(target);
        }
    }

    @Override
    public Fragment getItem(int position) {
        //ImageFragment is a normal fragment containing a ImageView
        return ImageFragment.newInstance(urlList.get(position), zoomEnabled);
    }

    @Override
    public int getCount() {
        return urlList.size();

    }

    class MyTarget implements Target {

        private String url;

        public MyTarget(String url) {
            this.url = url;
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            ScreenSlidePagerAdapter.this.urlList.add(url);
            ScreenSlidePagerAdapter.this.notifyDataSetChanged();
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    }

}