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

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

 

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

 

其实要真正能分析手势,需要处理好这四个参数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(); 
    }elseif (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(); 
    
    
    returnfalse
}

 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) {   
    returnmGestureDetector.onTouchEvent(event);   
}

 

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

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

相关文章:

  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-09-15
  • 2021-07-28
  • 2021-06-08
  • 2022-12-23
相关资源
相似解决方案