Android使用ViewPager实现无限循环滑动及轮播(附源码)

MainActivity如下:
package cc.ww;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
 * 原创作者:
 * 谷哥的小弟 http://blog.csdn.net/lfdfhl
 * 
 * Demo描述:
 * 1 ViewPager的自动轮播
 * 2 同时支持手动切换ViewPager的Item
 * 3 解决了当图片小于三张ViewPager轮播时崩溃的问题
 */
public class MainActivity extends Activity {
	private Context mContext;
	private Handler mHandler;
	private Runnable mRunnable;
	private ViewPager mViewPager;
	private int viewPagerItemSize=0;
	private ImageView[] dotImageViews;
	private final int INTERVAL =1000 * 3;
	private ArrayList<Integer> mArrayList;
	private LinearLayout mDotsLinearLayout;
	private final static int SET_VIEWPAGER_ITEM=9527;
	private LauncherViewPagerAdapter mViewPagerAdapter;
	private PageChangeListenerImpl mPageChangeListenerImpl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//去掉状态栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				             WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		init();
	}
	
	
	//初始化
	private void init() {
		initData();
		if(viewPagerItemSize>0){
			initDots();
			initViewPager();
			setAutoChangeViewPager();
		}
	}
	
	
	//准备ViewPager将显示的数据
	private void initData(){
		mContext = this;
		mArrayList=new ArrayList<Integer>();
		mArrayList.add(R.drawable.a);
		mArrayList.add(R.drawable.b);
		mArrayList.add(R.drawable.c);
		mArrayList.add(R.drawable.d);
		viewPagerItemSize=mArrayList.size();
	}
	
	
	//初始化ViewPager
	private void initViewPager(){
		mViewPager = (ViewPager) findViewById(R.id.guide_viewpager);
		mViewPagerAdapter = new LauncherViewPagerAdapter(mContext);
		mViewPagerAdapter.setAdapterData(mArrayList);
		mViewPager.setAdapter(mViewPagerAdapter);
		int currentItem = Integer.MAX_VALUE/2 - Integer.MAX_VALUE/2 % viewPagerItemSize;
		mViewPager.setCurrentItem(currentItem);
		setdotImageViews(currentItem%viewPagerItemSize);
		mViewPager.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				mViewPager.requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});
	}
	

    //初始化底部小圆点
    private void initDots() {
    	mDotsLinearLayout = (LinearLayout) findViewById(R.id.dotsLinearLayout);
        dotImageViews = new ImageView[viewPagerItemSize];
        for (int i = 0; i < dotImageViews.length; i++) {
            LinearLayout layout = new LinearLayout(mContext);
            ImageView imageView = new ImageView(mContext);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
            if (i == 0) {
                imageView.setBackgroundResource(R.drawable.guide_dot_white);
            } else {
                layout.setPadding(20, 0, 0, 0);
                imageView.setBackgroundResource(R.drawable.guide_dot_black);
            }
            dotImageViews[i] = imageView;
            layout.addView(imageView);
            mDotsLinearLayout.addView(layout);
        }
    }
    
    
    //开启ViewPager的自动轮播
 	@SuppressWarnings("deprecation")
	private void setAutoChangeViewPager() {
		mPageChangeListenerImpl = new PageChangeListenerImpl();
		mViewPager.setOnPageChangeListener(mPageChangeListenerImpl);

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case SET_VIEWPAGER_ITEM:
					if (mViewPager != null && mViewPagerAdapter != null) {
						int currentItemIndex = mViewPager.getCurrentItem();
						int itemsCount = mViewPagerAdapter.getCount();
						if ((currentItemIndex + 1) < itemsCount) {
							mViewPager.setCurrentItem(currentItemIndex + 1, true);
						} else {
							mViewPager.setCurrentItem(0, false);
						}
					}
					break;
				}
			}
		};

		mRunnable = new Runnable() {
			@Override
			public void run() {
				Message message = mHandler.obtainMessage();
				message.what = SET_VIEWPAGER_ITEM;
				mHandler.sendMessage(message);
				mHandler.removeCallbacks(mRunnable);
				mHandler.postDelayed(this, INTERVAL);
			}
		};

		mHandler.postDelayed(mRunnable, INTERVAL);
	}
 	
 	
 	//设置小圆点的显示
 	private void setdotImageViews(int selected){
 		 for (int i = 0; i < dotImageViews.length; i++) {
             dotImageViews[selected].setBackgroundResource(R.drawable.guide_dot_white);
             if (selected != i) {
                 dotImageViews[i].setBackgroundResource(R.drawable.guide_dot_black);
             }
         }
 	}
    
    //ViewPager翻页后更新小圆点的显示
    private class PageChangeListenerImpl implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageSelected(int selected) {
        	 setdotImageViews(selected % viewPagerItemSize);
        }

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

        @Override
        public void onPageScrollStateChanged(int state) {
        	
        }

    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	if(null!=mViewPager){
    		mViewPager.removeAllViews();
            mViewPager = null;
    	}
    }
	
}

LauncherViewPagerAdapter如下:
package cc.ww;

import java.util.ArrayList;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

public class LauncherViewPagerAdapter extends PagerAdapter {
	private Context mContext;
	private ArrayList<Integer> pagesArrayList;
	private View itemView;

	public LauncherViewPagerAdapter(Context context) {
		this.mContext = context;
	}
	
	/**
	 * 设置ViewPager将要显示的数据.
	 * 当图片数量小于三张的时候,通过复制组拼数据
	 */
	public void setAdapterData(ArrayList<Integer> arrayList){
		pagesArrayList=arrayList;
		if (pagesArrayList.size()<1) {
			Toast.makeText(mContext, "ViewPager item size=0", Toast.LENGTH_LONG).show();
		}else if(pagesArrayList.size()<2){
			 pagesArrayList.add(pagesArrayList.get(0));
			 pagesArrayList.add(pagesArrayList.get(0));
			 pagesArrayList.add(pagesArrayList.get(0));
		}else if(pagesArrayList.size()<3){
			pagesArrayList.add(pagesArrayList.get(0));
			pagesArrayList.add(pagesArrayList.get(1));
		}
		System.out.println("-----> PagerAdapter中item的个数="+pagesArrayList.size());
	}
	

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

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		 if (pagesArrayList.size() > 0) {
			itemView=LayoutInflater.from(mContext).inflate(R.layout.guide_pager_adapter, null);
     		itemView.setFocusable(true);
     		ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
     		imageView.setBackgroundResource(pagesArrayList.get(position%pagesArrayList.size()));
     		container.addView(itemView);
     		return itemView;
         }
         return null;
		
	}


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

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		 container.removeView((View) object);
	}
}

activity_main.xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/guide_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/dotsLinearLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="100px"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
    </LinearLayout>
    


</RelativeLayout>

guide_pager_adapter.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


上一篇:【android-tips】如何在android应用中插入百度广告(附源码)


下一篇:objectAnimation与ValueAnimation的使用