android 手势左右滑动

继承SimpleOnGestureListener 类,判断左右滑动并处理事件:

 

class MyGestureDetector extends SimpleOnGestureListener {
  private static final int SWIPE_MIN_DISTANCE = 120;
  private static final int SWIPE_MAX_OFF_PATH = 250;
  private static final int SWIPE_THRESHOLD_VELOCITY = 200;
  
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   try {
    if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
     return false;
    // right to left swipe
    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
      && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
     if(CommonUtil.DEBUG)Log.i("test ", "left");
     
    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
      && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
     if(CommonUtil.DEBUG)Log.i("test ", "right");
     
      }
   } catch (Exception e) {
    Log.e(TAG, "onFling error", e);
   }
   return false;
  }
 }

 

 

在activity中定义GestureDetector 变量

 private GestureDetector gestureDetector;
 View.OnTouchListener gestureListener;

在oncreate()中赋值:

  gestureDetector = new GestureDetector(new MyGestureDetector());
  gestureListener = new View.OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    if (gestureDetector.onTouchEvent(event)) {
     return true;
    }
    return false;
   }
  };

 

 

重写dispatchTouchEvent(MotionEvent event)方法

 @Override
 public boolean dispatchTouchEvent(MotionEvent event) {

  if (gestureDetector.onTouchEvent(event)) {
   event.setAction(MotionEvent.ACTION_CANCEL);
  }
  return super.dispatchTouchEvent(event);

 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_see

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值