ViewPager(三)——深入理解 OnPageChangeListener中的onPageScrollStateChanged(int state)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cctvjiatao.viewpagerdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.cctvjiatao.viewpagerdemo;

import java.lang.reflect.Field;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.EdgeEffectCompat;
import android.util.Log;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
 * @作者: jiatao
 * @修改时间:2016-4-13 下午6:18:27
 * @文件名:MainActivity.java
 * @版权声明:www.cctvjiatao.com
 * @功能:    1、理解运用 PagerAdapter
 * 			2、深入理解 OnPageChangeListener中的onPageScrollStateChanged(int state)
 * 			3、ViewPager在拖拽到左边和右边的时候,禁止显示黄色或者蓝色的渐变图片的解决方法
 */

/*
 * ViewPager在拖拽到左边和右边的时候,禁止显示黄色或者蓝色的渐变图片的解决方法:打开用“//”注释掉的代码即可
 */

public class MainActivity extends Activity {

	private Context mContext;
	private ViewPager mViewPager;
	private StartPagerAdapter mStartPagerAdapter;
	private ImageView[] dotImageViews;
	private PageChangeListenerImpl mPageChangeListenerImpl;
	private LinearLayout mDotsLinearLayout;
	private boolean misScrolled = false;
	
	//ViewPager在拖拽到最左边或最右边的时候,会显示黄色或蓝色的渐变图片,如果要禁止显示这些渐变,需要用到下面这两个属性
//	private EdgeEffectCompat leftEdge;
//	private EdgeEffectCompat rightEdge;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		mViewPager = (ViewPager) findViewById(R.id.guide_viewpager);
		mDotsLinearLayout = (LinearLayout) findViewById(R.id.dotsLinearLayout);
		mStartPagerAdapter = new StartPagerAdapter(mContext);
		mPageChangeListenerImpl = new PageChangeListenerImpl();
		mViewPager.setAdapter(mStartPagerAdapter);
		mViewPager.setOnPageChangeListener(mPageChangeListenerImpl);
//		try {//通过反射得到对象
//			Field leftEdgeField = mViewPager.getClass().getDeclaredField("mLeftEdge");
//			Field rightEdgeField = mViewPager.getClass().getDeclaredField("mRightEdge");
//	    	Log.e(TAG, "=======leftEdgeField:" + leftEdgeField + ",rightEdgeField:" + rightEdgeField);//			if (leftEdgeField != null && rightEdgeField != null) {
//				leftEdgeField.setAccessible(true);
//				rightEdgeField.setAccessible(true);
//				leftEdge = (EdgeEffectCompat) leftEdgeField.get(mViewPager);
//				rightEdge = (EdgeEffectCompat) rightEdgeField.get(mViewPager);
//				Log.e(TAG, "=======OK啦,leftEdge:" + leftEdge + ",rightEdge:" + rightEdge);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		initDots();
	}

	// 初始化小圆点
	private void initDots() {
		dotImageViews = new ImageView[mStartPagerAdapter.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);
		}
	}

	
	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) {
//			if (leftEdge != null && rightEdge != null) {
//				leftEdge.finish();
//				rightEdge.finish();
//				leftEdge.setSize(0, 0);
//				rightEdge.setSize(0, 0);
//			}
		}

		/**
		 * 重点!通过输出日志认真理解 onPageScrollStateChanged(int state) 的运用,主要是对state参数的认识
		 */
		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
			case ViewPager.SCROLL_STATE_DRAGGING://1 dragging(拖动),理解为:只要触发拖动/滑动事件时,则 state = ViewPager.SCROLL_STATE_DRAGGING
				misScrolled = false;
				Log.e("onPageScrollStateChanged", "state:"+state+"---------->misScrolled:"+misScrolled+"---------->现在的页码索引:"+mViewPager.getCurrentItem());
				break;
			case ViewPager.SCROLL_STATE_SETTLING://2 settling(安放、定居、解决),理解为:通过拖动/滑动,安放到了目标页,则 state = ViewPager.SCROLL_STATE_SETTLING
				misScrolled = true;
				Log.e("onPageScrollStateChanged", "state:"+state+"---------->misScrolled:"+misScrolled+"---------->现在的页码索引:"+mViewPager.getCurrentItem());
				break;
			case ViewPager.SCROLL_STATE_IDLE://0 idle(空闲,挂空挡), 理解为:只要拖动/滑动结束,无论是否安放到了目标页,则 state = ViewPager.SCROLL_STATE_IDLE
				if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getCount() - 1 && !misScrolled) {//如果当前页是最后一页,并且滑动,则触发finish()
					/*此处可写一些逻辑,如finish() 或 startActivity()
					finish();*/
					Log.e("在末页向左滑", "state:"+state+"---------->misScrolled:"+misScrolled+"---------->现在的页码索引:"+mViewPager.getCurrentItem());
					Toast.makeText(mContext, "已经是最后一页", 2).show();
				}
				
				if (mViewPager.getCurrentItem() == 0 && !misScrolled) {//如果当前页是第一页,并且滑动,则触发finish()
					/*此处可写一些逻辑,如finish() 或 startActivity()
					finish();*/
					Log.e("在首页向右滑", "state:"+state+"---------->misScrolled:"+misScrolled+"---------->现在的页码索引:"+mViewPager.getCurrentItem());
					Toast.makeText(mContext, "已经是第一页", 2).show();
				}
				misScrolled = true;
				Log.e("onPageScrollStateChanged", "state:"+state+"---------->misScrolled:"+misScrolled+"---------->现在的页码索引:"+mViewPager.getCurrentItem());
				break;
			}
		}

	}

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

}

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_centerHorizontal="true"
        android:layout_marginBottom="100px"
        android:orientation="horizontal" >
    </LinearLayout>

</RelativeLayout>

StartPagerAdapter.java

package com.cctvjiatao.viewpagerdemo;

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;

/**
 * @作者: jiatao
 * @修改时间:2016-4-13 下午3:18:27
 * @文件名:StartPagerAdapter.java
 * @版权声明:www.cctvjiatao.com
 * @功能: PagerAdapter ———— FragmentPagerAdapter、FragmentStatePagerAdapter 是PagerAdapter的特殊实现类
 */
public class StartPagerAdapter extends PagerAdapter {

	private Context mContext;
	private int[] pagesArray = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d };

	public StartPagerAdapter(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;
	}
	
	/**
	 * ????????? http://blog.csdn.net/harvic880925/article/details/38487149
	 */
	@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);
	}
}


你可能感兴趣的:(ViewPager(三)——深入理解 OnPageChangeListener中的onPageScrollStateChanged(int state))