ViewPager的自动轮巡和无限循环效果

关于ViewPager的自动轮巡和无限循环效果,参考自源网页:
http://www.cnblogs.com/kobe8/p/4343478.html
源网页中代码无法自动轮番播放,需要手动滑动后才启用轮巡,修正后正常启用

public class MainActivity extends Activity {

    private ImageHandler handler = 
            new ImageHandler(new WeakReference<MainActivity>(this));

    private ViewPager viewPager;
    private ImageView view1;
    private ImageView view2;
    private ImageView view3;
    private List<ImageView> views;


    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.vp_main);
        LayoutInflater inflater = LayoutInflater.from(this);
        view1 = (ImageView) inflater.inflate(R.layout.vp1_image, null);
        view2 = (ImageView) inflater.inflate(R.layout.vp2_image, null);
        view3 = (ImageView) inflater.inflate(R.layout.vp3_image, null);
        view1.setImageResource(R.drawable.vp1);
        view2.setImageResource(R.drawable.vp2);
        view3.setImageResource(R.drawable.vp3);
        views = new ArrayList<ImageView>();
        views.add(view1);
        views.add(view2);
        views.add(view3);
        viewPager.setAdapter(new ImageAdapter(views));
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            //配合Adapter的currentItem字段进行设置
            // 当新的页面被选中时调用
            @Override
            public void onPageSelected(int arg0) {
                Message msg = Message.obtain(handler, ImageHandler.MSG_PAGE_CHANGED , arg0, 0);
                handler.sendMessage(msg);
            }
            // 当当前页面被滑动时调用
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }
            //覆写该方法实现轮播效果的暂停和恢复
            // 当滑动状态改变时调用
            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
                switch (arg0) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                    // 正在拖动页面时执行此处
                    handler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    // 未拖动页面时执行此处
                    handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                    break;
                default:
                    break;
                }
            }
        });
        viewPager.setCurrentItem(Integer.MAX_VALUE/2);
        //开始轮播效果
        //如果执行已经被注释的代码,则需要在点击viewpager之后才能进行轮番播放
        //因为在ImageHandler中,为避免在复杂环境下消息出现重复问题(实际情况是,如果不判断则一定会重复),对activity.handler.hasMessages(MSG_UPDATE_IMAGE)进行了判断
        //如果activity.handler.hasMessages(MSG_UPDATE_IMAGE),则
        //activity.handler.removeMessages(MSG_UPDATE_IMAGE)执行
        //会导致MSG_UPDATE_IMAGE消息被清除而不自动轮巡,因此不能首先发送MSG_UPDATE_IMAGE
        //handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
        handler.sendEmptyMessage(ImageHandler.MSG_BREAK_SILENT);


    }

    private static class ImageHandler extends Handler{
        /** * 请求更新显示的View。 */
        protected static final int MSG_UPDATE_IMAGE  = 1;
        /** * 请求暂停轮播。 */
        protected static final int MSG_KEEP_SILENT   = 2;
        /** * 请求恢复轮播。 */
        protected static final int MSG_BREAK_SILENT  = 3;
        /** * 记录最新的页号,当用户手动滑动时需要记录新页号,否则会使轮播的页面出错。 * 例如当前如果在第一页,本来准备播放的是第二页,而这时候用户滑动到了末页, * 则应该播放的是第一页,如果继续按照原来的第二页播放,则逻辑上有问题。 */
        protected static final int MSG_PAGE_CHANGED  = 4;

        //轮播间隔时间
        protected static final long MSG_DELAY = 3000;
        //使用弱引用避免Handler泄露.这里的泛型参数可以不是Activity,也可以是Fragment等
        private WeakReference<MainActivity> weakReference;
        private int currentItem = 0;

        protected ImageHandler(WeakReference<MainActivity> wk) {
            // TODO Auto-generated constructor stub
            weakReference = wk;
        }

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            MainActivity activity = weakReference.get();
            if (activity==null) {
                //Activity已经回收,无需再处理UI了
                return;
            }
            //检查消息队列并移除未发送的消息,这主要是避免在复杂环境下消息出现重复等问题。
            //不判断则会同时接受多个MSG_UPDATE_IMAGE,并重复轮番播放
            if (activity.handler.hasMessages(MSG_UPDATE_IMAGE)) {
                activity.handler.removeMessages(MSG_UPDATE_IMAGE);
            }
            switch (msg.what) {
            case MSG_UPDATE_IMAGE:
                currentItem++;
                activity.viewPager.setCurrentItem(currentItem);
                //准备下次播放
                Log.d("TAG", "currentItem="+currentItem+"&&msg="+msg);
                activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                break;
            case MSG_KEEP_SILENT:
                //只要不发送消息就暂停了
                break;
            case MSG_BREAK_SILENT:
                activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                break;
            case MSG_PAGE_CHANGED:
                //记录当前的页号,避免播放的时候页面显示不正确
                currentItem = msg.arg1;
                break;
            default:
                break;
            }
        }
    }


    private class ImageAdapter extends PagerAdapter{
        private List<ImageView> viewList;
        public ImageAdapter(List<ImageView> viewList) {
            this.viewList = viewList;
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0==arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // DO NOTHING
            //Warning:不要在这里调用removeView
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //对ViewPager页号求模取出View列表中要显示的项
            position = position%viewList.size();
            //如果位置是负数,则做处理
            if (position<0) {
                position = viewList.size()+position;
            }
            ImageView view = viewList.get(position);
            //如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException
            ViewParent vp = view.getParent();
            if (vp!=null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

    }

}

你可能感兴趣的:(viewpager)