Skip to content

How to Cache PagerAdapter Item  #27

Description

@SingleJie

public class SimpleGalleryAdapter extends PagerAdapter {

private List<T> mDatas;
private String imgFieldName;
private SparseArray<ImageView> mCaches = new SparseArray<>();
private String host;
private OnImageLoadListener<T> mListener;

@Override
public int getCount() {
    return EmptyUtils.emptyOfList(mDatas) ? 0 : mDatas.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

    Context context = container.getContext();
    ImageView img_display = mCaches.get(position);

    if (img_display == null) {
        img_display = new ImageView(context);
        img_display.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mCaches.put(position, img_display);
    }

    T mItem = mDatas.get(position);

    if (mListener != null) {
         mListener.onImageLoad(img_display, mItem, imgFieldName, host);
    }
    container.addView(img_display);
    return img_display;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    if (mCaches.keyAt(position) != -1) {
        container.removeView(mCaches.get(position));
        mCaches.remove(position);
    }
}

public SimpleGalleryAdapter(List<T> mDatas, String host, String imgFieldName, OnImageLoadListener<T> mListener) {
    this.mDatas = mDatas;
    this.imgFieldName = imgFieldName;
    this.host = host;
    this.mListener = mListener;
}

public SimpleGalleryAdapter(List<T> mDatas, String host, String imgFieldName) {
    this.mDatas = mDatas;
    this.imgFieldName = imgFieldName;
    this.host = host;
    this.mListener = new GlideImageLoader<T>();
}

}

that is my adapter , I user ViewPager no error , but use LoopViewPager throw this error
The specified child already has a parent. You must call removeView() on the child's parent first.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions