Android 屏幕手势滑动中onFling()函数的技巧分析
关于如何处理手势操作以及那四个基本固定的顺序我就不讲解了,这里直接跳到我们获得瞬间滑动后回调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()里面完成任务。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2012-01-17 test
2012-01-17 松下等离子电视 u盘播放
2012-01-17 Android NDK builder for Eclipse in Windows