ViewPager实现左右循环滑动

目标
类似用户引导页,可以滑动,左右滑动已经有大量实现,但循环滑动实现较少或者实现的效果不是很好。
效果不好主要体现在大概以下四个方面:图片少的时候会崩溃、单张图片的时候引导点存在、最后一张与第一张图片之间的滑动效果不自然、没有自动播放。
故此处实现任何图片的左右自然的循环滑动以及自动播放。
使用场景
1.用户引导页,多张图片
2.图片浏览,图片本地或者网络(网络时会出现图片可能为0、1的特殊情况)
实现方式
1.首末图片添加。最后一张图片后再加一张图片(第一张),第一张图片前加一个图片(最后一张),然后这样ViewPager一共有N+2页,在ViewPager的setOnPageChangeListener的onPageSelected()里面检测到当前页面索引为0时,setCurrentItem为N-2(左滑),当索引为N+1时,设置setCurrentItem为1(右滑)。其他的不便,这样便可实现循环左右滑动,但是首位图片滑动效果不自然,会突然跳过去。
2.重写ViewPager.OntouchListener。方法基本同上。效果不好
private int lastX = 0;// 获得当前X坐标
private boolean mSlideLock = false;// 滑动锁,解决从最后一页向右滑动以及从第一页向左滑出现的多次滑动的问题
private final static int LOCK_TIME = 5000;

    mViewPager.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getX();
                break;
            case MotionEvent.ACTION_UP:
                Log.i("ViewPrivatePhotoTag", "当前项:"+mViewPager.getCurrentItem() +",总项数:" +mViewPager
                        .getAdapter().getCount());
                if (!mSlideLock) {
                    if ((lastX - event.getX() > 100)
                            && (mViewPager.getCurrentItem() == mViewPager
                                    .getAdapter().getCount() - 1)) {// 从最后一页向右滑动
                        mViewPager.setCurrentItem(0,true);
                        
                        mSlideLock = true;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() { }, LOCK_TIME);
                    } else if ((lastX - event.getX() < -100)
                            && (mViewPager.getCurrentItem() == 0)) {// 从第一页向左滑
                        mViewPager.setCurrentItem(mViewPager.getAdapter().getCount()-1);
                        mSlideLock = true;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mSlideLock = false;
                            }

                        }, LOCK_TIME);
                    }
                }
            }
            return false;
        }
    });

3.巧用求余。此处参考如下例子。
一个示例如下http://blog.csdn.net/xiaanming/article/details/8966621
一个实现
本实现参考第三个,实现了左右循环滑动以及定时播放
/**

  • @original author xiaanming
  • update by wangyun 2013/7/24
  • 增加图片自动播放
  • 解决图片少时崩溃的情形
  • 屏蔽单张图片是的点点
  • 图片为1时显示有问题
  • to do:需要处理size()为0时的异常
    */

package com.example.viewpagerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class ViewPagerDemoActivity extends Activity {
/**
* ViewPager
*/
private ViewPager viewPager;

/**
 * 装点点的ImageView数组
 */
private ImageView[] tips;

/**
 * 装ImageView数组
 */
private ImageView[][] mImageViews;

/**
 * 图片资源id
 */
private int[] imgIdArray;

private static final int MSG_CHANGE_PHOTO = 1;

/** 图片自动切换时间 */
private static final int PHOTO_CHANGE_TIME = 5000;
private Handler mHandler = new Handler() {
    @Override
    public void dispatchMessage(Message msg) {
        switch (msg.what) {
        case MSG_CHANGE_PHOTO:
            int index = viewPager.getCurrentItem();
            viewPager.setCurrentItem(index + 1);
            mHandler.sendEmptyMessageDelayed(MSG_CHANGE_PHOTO,
                    PHOTO_CHANGE_TIME);
            break;
        }
        super.dispatchMessage(msg);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);
    viewPager = (ViewPager) findViewById(R.id.viewPager);


    // 载入图片资源ID
    imgIdArray = new int[] { R.drawable.item1 ,R.drawable.item2,R.drawable.item3,R.drawable.item4,R.drawable.item5};

    // 将点点加入到ViewGroup中
    tips = new ImageView[imgIdArray.length];

    if (imgIdArray.length <= 1)
        group.setVisibility(View.GONE);
    for (int i = 0; i < tips.length; i++) {
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new LayoutParams(10, 10));
        tips[i] = imageView;
        if (i == 0) {
            tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
        } else {
            tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
        }

        group.addView(imageView);
    }

    mImageViews = new ImageView[2][];
    // 将图片装载到数组中,其中一组类似缓冲,防止图片少时出现黑色图片,即显示不出来
    mImageViews[0] = new ImageView[imgIdArray.length];
    mImageViews[1] = new ImageView[imgIdArray.length];

    for (int i = 0; i < mImageViews.length; i++) {
        for (int j = 0; j < mImageViews[i].length; j++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(imgIdArray[j]);
            mImageViews[i][j] = imageView;
            Log.i("TwoActivity_WY", i + "," + j + "\t");
        }
    }

    // 设置Adapter
    viewPager.setAdapter(new MyAdapter());
    // 设置监听,主要是设置点点的背景
    viewPager.setOnPageChangeListener(new OnPageChangeListener() {
        
        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            setImageBackground(arg0 % imgIdArray.length);
        }
    });
    
    viewPager.setOnTouchListener(new OnTouchListener() {
        
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(imgIdArray.length==0||imgIdArray.length==1)
                return true;
            else
                return false;
        }
    });

    // 设置ViewPager的默认项, 设置为长度的50倍,这样子开始就能往左滑动
    viewPager.setCurrentItem((imgIdArray.length) * 50);
    mHandler.sendEmptyMessageDelayed(MSG_CHANGE_PHOTO, PHOTO_CHANGE_TIME);
}

public class MyAdapter extends PagerAdapter {

    @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) {
        if (imgIdArray.length == 1)
            ((ViewPager) container).removeView(mImageViews[position
                    / imgIdArray.length % 2][0]);
        else
            ((ViewPager) container).removeView(mImageViews[position
                    / imgIdArray.length % 2][position % imgIdArray.length]);
    }

    /**
     * 载入图片进去,用当前的position 除以 图片数组长度取余数是关键
     */
    @Override
    public Object instantiateItem(View container, int position) {
        if (imgIdArray.length == 1)
            return mImageViews[position / imgIdArray.length % 2][0];
        else
            ((ViewPager) container).addView(mImageViews[position
                    / imgIdArray.length % 2][position % imgIdArray.length],
                    0);
        return mImageViews[position / imgIdArray.length % 2][position
                % imgIdArray.length];
    }

}



/**
 * 设置选中的tip的背景
 *
 * @param selectItemsIndex
 */
private void setImageBackground(int selectItemsIndex) {
    for (int i = 0; i < tips.length; i++) {
        if (i == selectItemsIndex) {
            tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
        } else {
            tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
        }
    }
}

}

下载地址
CSDN

即得

文档下载地址
即得

以下是一位网友封装的一个ViewPager库,实现了我说的基本所有的功能
http://download.csdn.net/detail/waylife/6197781

你可能感兴趣的:(ViewPager实现左右循环滑动)