ViewPager详解(二)——自动轮播和手动切换完整示例

简介: MainActivity如下: package cn.ww;import android.app.Activity;import android.

MainActivity如下:

package cn.ww;
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;
/**
 * @author http://blog.csdn.net/lfdfhl
 * 
 * Demo描述:
 * 1 ViewPager的自动轮播
 * 2 同时支持手动切换ViewPager的Item
 */
public class MainActivity extends Activity {
	private Context mContext;
	private Handler mHandler;
	private Runnable mRunnable;
	private ViewPager mViewPager;
	private ImageView[] dotImageViews;
	private final int INTERVAL =1000 * 3;
	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() {
		mContext = this;
		mViewPager = (ViewPager) findViewById(R.id.guide_viewpager);
		mDotsLinearLayout = (LinearLayout) findViewById(R.id.dotsLinearLayout);
		mViewPagerAdapter = new LauncherViewPagerAdapter(mContext);
		mPageChangeListenerImpl = new PageChangeListenerImpl();
		mViewPager.setAdapter(mViewPagerAdapter);
		mViewPager.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				mViewPager.requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});
		initDots();
		setAutoChangeViewPager();
	}
	

    //初始化小圆点
    private void initDots() {
        dotImageViews = new ImageView[mViewPagerAdapter.getCount()];
        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() {
		mViewPager.setOnPageChangeListener(mPageChangeListenerImpl);

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case SET_VIEWPAGER_ITEM:
					if (mViewPagerAdapter != null && mViewPagerAdapter.getCount() > 0) {
						int currentItemIndex = mViewPager.getCurrentItem();
						int itemsCount = mViewPager.getAdapter().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 class PageChangeListenerImpl implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageSelected(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);
                }
            }
        }

        @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 cn.ww;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

public class LauncherViewPagerAdapter extends PagerAdapter {
	private Context mContext;
	private int[] pagesArray = {R.drawable.a,R.drawable.b, R.drawable.c, R.drawable.d};

	public LauncherViewPagerAdapter(Context context) {
		this.mContext = context;
	}

	@Override
	public int getCount() {
		return pagesArray.length;
	}

	@Override
	public Object instantiateItem(View container, int position) {
		View itemView = LayoutInflater.from(mContext).inflate(R.layout.guide_pager_adapter, null);
		itemView.setFocusable(true);
		ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
		imageView.setBackgroundResource(pagesArray[position]);
		((ViewPager) container).addView(itemView);
		return itemView;
	}


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

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

activity_main如下:

<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>


相关文章
ViewPager 显示 两侧的View,各显示一点
ViewPager 显示 两侧的View,各显示一点
ViewPager 显示 两侧的View,各显示一点
ViewPager如何区分自动切换和手势滑动切换
ViewPager是一个很常见的组件,不仅支持收拾滑动切换页面,我们还可以通过`viewPager.setCurrentItem(index)`来切换到指定的页面,那么他们如何区分呢? 我们知道ViewPager可以添加`ViewPager.OnPageChangeListener`监听器,可以监听切换的状态。通过观察`ViewPager.OnPageChangeListener#onPageScrollStateChanged(int state)`方法中state的输出,发现了手势切换和自动切换的规律。
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
669 0
BottomNavigationView使用,配合ViewPager、修改图标大小、去掉文字等
|
Android开发
关于Android ViewPager禁止滑动
ViewPager默认是可以手动切换的,实现自动切换,可以通过定时器来完成,而有些时候,我们是需要禁止ViewPager手动切换的, 这个时候就需要自定义ViewPager了,其实也很简单,原理就是拦截触摸事件,让ViewPager不处理onTouch事件,直接交给他的子控件去处理就行。
287 0
|
XML 数据格式
千变万化的ViewPager指示器-MagicIndicator
千变万化的ViewPager指示器-MagicIndicator
千变万化的ViewPager指示器-MagicIndicator
|
Java 容器
解决ViewPager+多Fragment切换出现空白页面的问题
解决ViewPager+多Fragment切换出现空白页面的问题
607 0
解决ViewPager+多Fragment切换出现空白页面的问题
ViewPager(通过反射修改viewpager切换速度)
(创建于2016/11/17) import java.lang.reflect.Field; import android.content.
1122 0
2-VIII--ViewPager滑动监听与自定义滑动特效
零、前言 [1]. 使用上文项目:1-VIII--ViewPager的基本使用 [2].对ViewPager的addOnPageChangeListener三个回调方法分析 [3].
1272 0