使用OnTouchListener监听滑动事件

OnTouchListener可以实现简单的滑动事件监听。


实现思路:

当按下手指的时候记录手指的坐标作为起始坐标,当手指抬起的时候把当前手指坐标与起始坐标对比,由此可以判断手指滑动的方向。

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public abstract class ExtendedTouchListener implements OnTouchListener {
	private final int MOVE_LEFT = 1011;
	private final int MOVE_RIGHT = 1012;
	private final int MOVE_TOP = 1013;
	private final int MOVE_BOTTOM = 1014;

	private int preX;
	private int preY;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			preX = (int) event.getX();
			preY = (int) event.getY();
			break;
		case MotionEvent.ACTION_UP:
			spearEvent(compare((int) event.getX(), (int) event.getY()), event);
			break;
		}
		return true;
	}

	private void spearEvent(int compare, MotionEvent event) {
		onFingerDown(event);
		switch (compare) {
		case MOVE_LEFT:
			onLeftTouch(event);
			break;
		case MOVE_RIGHT:
			onRightTouch(event);
			break;
		case MOVE_TOP:
			onTopTouch(event);
			break;
		case MOVE_BOTTOM:
			onBottomTouch(event);
			break;
		default:
			break;
		}
	}

	private int compare(int x, int y) {
		int dltX = x - preX, dltY = y - preY;
		if (Math.abs(dltX) > Math.abs(dltY) {
			return dltX > 0 ? MOVE_RIGHT : MOVE_LEFT;
		} else {
			return dltX > 0 ? MOVE_TOP : MOVE_BOTTOM;
		}
	}

	abstract void onFingerDown(MotionEvent event);

	abstract void onLeftTouch(MotionEvent event);

	abstract void onRightTouch(MotionEvent event);

	abstract void onTopTouch(MotionEvent event);

	abstract void onBottomTouch(MotionEvent event);
}

这样
 
  


你可能感兴趣的:(使用OnTouchListener监听滑动事件)