安卓自定义ViewPager防止滑动冲突

安卓里面有时候组件的嵌套会导致滑动的冲突,比如viewPager嵌套了viewPager,就会导致滑动冲突,系统不知道要滑动哪一个组件,这时候我们就得利用安卓的事件分发机制来控制组件的滑动规则。

/**
 * 自定义ViewPager
 * @author CXX
 *
 */
public class MViewPager extends ViewPager {
	private float mDownX;
	private float mDownY;

	private static final int NONE = 0;
	private static final int VERTICAL = 1;
	private static final int HORIZONTAL = 2;

	private static final int MINDIS = 30;
	private int currState;

	public MViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		currState = NONE;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent arg0) {
		return super.onInterceptTouchEvent(arg0);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mDownX = ev.getX();
			mDownY = ev.getY();
			Log.d("CXX", "当前状态Down"+currState);
			break;
		case MotionEvent.ACTION_MOVE:
			if (currState == NONE) {
				Log.d("CXX","还在判定中" );
				int dis = (int) Math.sqrt((Math.pow((ev.getX() - mDownX),2) + (Math.pow((ev.getY() - mDownY),2))));
				if(dis > MINDIS){
				if (Math.abs(ev.getX() - mDownX) > Math.abs(ev.getY() - mDownY)) {
					// 横向移动
					Log.d("CXX", "当前状态heng"+currState);
					getParent().requestDisallowInterceptTouchEvent(true);
					currState = HORIZONTAL;
				} else {
					// 竖直移动
					Log.d("CXX", "当前状态shu"+currState);
					getParent().requestDisallowInterceptTouchEvent(false);
					currState = VERTICAL;
				}
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			currState = NONE;
			break;
		case MotionEvent.ACTION_CANCEL:
			break;
		}
		return super.dispatchTouchEvent(ev);
	}
	

}


你可能感兴趣的:(android,viewpager)