Android 屏幕手势滑动中onFling()函数的技巧分析

    xiaoxiao2022-06-23  30

    Android 屏幕手势滑动中onFling()函数的技巧分析

    时间:2012-10-22 20:21  来源:未知  作者:admin  点击: 520 次

    摘要 关于如何处理手势操作以及那四个基本固定的顺序我就不讲解了,这里直接跳到我们获得瞬间滑动后回调onFling()这个抽象函数时,应该如何根据参数比较准确的判断滑动方向。如果你没有前面的基础知识,你可以去看看这篇文章: http://jcodecraeer.com/a/anzhuoka

    关于如何处理手势操作以及那四个基本固定的顺序我就不讲解了,这里直接跳到我们获得瞬间滑动后回调onFling()这个抽象函数时,应该如何根据参数比较准确的判断滑动方向。如果你没有前面的基础知识,你可以去看看这篇文章:http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1020/448.html

    我看到网上大部分资料,对这个抽象函数的实现都是相当简单的:

    1 2 3 4 5 6 @Override   public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  float velocityY) {       //dosomething  return false ;   }

     

    这些文章其实能解决的问题只有一个,那就是教你如何能在有手势操作的时候,捕获到这个动作,却没有去分析这个动作。

     

    其实要真正能分析手势,需要处理好这四个参数MotionEvent e1, MotionEvent e2, float velocityX, float velocityY

     

     先来看一个例子: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private int verticalMinDistance = 20;  private int minVelocity         = 0;       public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {            if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {                // 切换Activity           // Intent intent = new Intent(ViewSnsActivity.this, UpdateStatusActivity.class);           // startActivity(intent);           Toast.makeText( this , "向左手势" , Toast.LENGTH_SHORT).show();       } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {                // 切换Activity           // Intent intent = new Intent(ViewSnsActivity.this, UpdateStatusActivity.class);           // startActivity(intent);           Toast.makeText( this , "向右手势" , Toast.LENGTH_SHORT).show();       }            return false ;  }

     OnFling的四个参数意思分别为

    e1: The first down motion event that started the fling.手势起点的移动事件 e2: The move motion event that triggered the current onFling.当前手势点的移动事件 velocityX: The velocity of this fling measured in pixels per second along the x axis.每秒x轴方向移动的像素 velocityY: The velocity of this fling measured in pixels per second along the y axis.每秒y轴方向移动的像素

    说的更简单点就是,鼠标手势相当于一个向量(当然有可能手势是曲线),e1为向量的起点,e2为向量的终点,velocityX为向量水平方向的速度,velocityY为向量垂直方向的速度

    1 if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity)

     

     则上面的语句能知道啥意思了吧,就是说向量的水平长度(滑了有多长)必须大于verticalMinDistance,并且水平方向速度大于minVelocity。

    从而我们可以如此判断手势是否满足一定的条件从而进行相应响应,也可以根据这个写出更复杂的手势判断。

     

    虽然我这篇文章不去探究手势操作的基本步凑,但还是有必要谈谈我们的listenner在重载onTouch()这个函数的时候应该思考的问题:

     

    1 2 3 public boolean onTouch(View v, MotionEvent event) {         return mGestureDetector.onTouchEvent(event);    }

     

    查看GestureDetector类的onTouchEvent的源码就能知道,进入该函数后会进入case MotionEvent.ACTION_UP这个路径,从而调用onFling函数。

    我要说的就是这句话,因为在我看来GestureDetector未必能满足处理所有的手势需求,肯能有那么一天,需要我们抛开GestureDetector   直接在onTouch()里面完成任务。

    转载请注明原文地址: https://ju.6miu.com/read-1123347.html

    最新回复(0)