ViewPage 轮播图优化,解决oom和白屏问题

发布时间:2023-02-20 17:00

public class NativePagerAdapter extends PagerAdapter {
    private List mList = new ArrayList<>();
    private Context mContext;
    private MyItemClick mMyItemClick;

    public interface MyItemClick {
        void onClick(int position);
    }

    public void setMyItemClick(MyItemClick myItemClick) {
        mMyItemClick = myItemClick;
    }

    public NativePagerAdapter(Context context, List list) {
        mContext = context;
        for (int i = 0; i < list.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_native_banner, null);
            ImageView imageview = (ImageView) view.findViewById(R.id.image);
            imageview.setId(i);
            Glide.with(mContext).load(list.get(i).imgUrl).into(imageview);
            imageview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int id = v.getId();
                    if (mMyItemClick != null) {
                        mMyItemClick.onClick(id);
                    }
                }
            });
            mList.add(view);
        }

    }

    @Override
    public int getCount() {
        //返回一个比较大的值,目的是为了实现无限轮播
        return Integer.MAX_VALUE;
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        position = position % mList.size();
        View view = mList.get(position);
        ViewGroup parent = (ViewGroup)view.getParent();
        if(parent!=null){
            parent.removeView(view);
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        container.removeView((View) object);
//        container.removeView(mList.get(position % mList.size()));
        Log.d(\"pageradpter\", \"destroyItem: \" + container.getChildCount());
    }
}



将数据转为View存储起来,而不是在instantiateItem中根据数据重组布局,destroyItem中不对view销毁,不然会显示空白图片,instantiateItem中判断view 的parent,存在则销毁,可保证container中存储的view只有list.size.


ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号