android onTouchEvent 左右手势滑动事件处理

要实现手指在屏幕上左右滑动的事件需要实例化对象GestureDetector,new GestureDetector(MainActivity.this,onGestureListener);首先实现监听对象GestureDetector.OnGestureListener,根据x或y轴前后变化坐标来判断是左滑动还是右滑动并根据不同手势滑动做出事件处理doResult(int action),

然后覆写onTouchEvent方法,在onTouchEvent方法中将event对象传给gestureDetector.onTouchEvent(event);处理。

 

MainActivity.java

import android.view.GestureDetector;

public class MainActivity extends TabActivity implements OnClickListener {

	final int RIGHT = 0;
	final int LEFT = 1;
	private GestureDetector gestureDetector;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		gestureDetector = new GestureDetector(MainActivity.this,onGestureListener);
	}

	private GestureDetector.OnGestureListener onGestureListener = 
		new GestureDetector.SimpleOnGestureListener() {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			float x = e2.getX() - e1.getX();
			float y = e2.getY() - e1.getY();

			if (x > 0) {
				doResult(RIGHT);
			} else if (x < 0) {
				doResult(LEFT);
			}
			return true;
		}
	};

	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	public void doResult(int action) {

		switch (action) {
		case RIGHT:
			System.out.println("go right");
			break;

		case LEFT:
			System.out.println("go left");
			break;

		}
	}
}


 参考http://www.cnblogs.com/meieiem/archive/2011/09/16/2178313.html
 

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值