ViewPager實現左右無限迴圈滑動

yangxi_001發表於2014-10-17
public class MyViewPagerAdapter extends PagerAdapter {

    private Context mContext;
    private ArrayList<ImageView> mImageViews = new ArrayList<ImageView>();

    public MyViewPagerAdapter(Context mContext, ArrayList<String> mImageUrls) {
        this.mContext = mContext;
        initPagerView(mImageUrls);
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        // 實現左右迴圈時不能銷燬
        // ((ViewPager) container).removeView(mImageViews.get(position %
        // mImageViews.size()));
    }

    @Override
    public Object instantiateItem(View container, int position) {
        // 實現左右迴圈時新增捕獲異常
        try {
            ((ViewPager) container).addView(mImageViews.get(position % mImageViews.size()), 0);
        } catch (Exception e) {
        }
        return mImageViews.get(position % mImageViews.size());
    }

    private void initPagerView(ArrayList<String> mImageUrls) {
        for (int i = 0; i < mImageUrls.size(); i++) {
            ImageView imageView = new ImageView(mContext);
            TupoApplication.finalBitmap.display(imageView, mImageUrls.get(i),
                    BitmapUtils.getIconDisplayConfig());
            mImageViews.add(imageView);
        }
    }

}

使用:

ViewPager viewPager = new ViewPager(context);
viewPager.setAdapter(new MyViewPagerAdapter(context, imageUrls));

// 實現向左滑動
viewPager.setCurrentItem(imageUrls.size() * 100);

相關文章