GestureDetector的使用
2016-05-25 11:53
330 查看
GestureDetector
GestureDetector:手势检测,用于辅助检测用户单击、滑动、长按、双击等行为。本文简单介绍GestureDetector的基本使用方法和用处,以及如何使用
obTouchEvent(XXX)代替
GestureDetector判断用户手指左右滑动的方法。
GestureDetector的基本用法
step 1:目标实现OnGestureListener接口
public class XXXActivity extends Activity implements GestureDetector.GestureListener{ //下面会有6个方法,开发的时候,不建议直接在Activity中使用,先封装后使用是更好的办法 }
step 2: 创建一个GestureDetector对象,并初始化它
private GestureDetector gestureDetector ; ..... protect void onCreat(Bundle saveInstanceStated){ ...... //这样的写法有一个前提,就是这个Activity实现了OnGestureListener接口 gestureDetecture = new GestureDetector(this,this); }
step 3:重写目标
onTouchEvent(XXX)的方法
public boolean onTouchEvent(MotionEvent event){ return gestureDetector.onTouchEvent(event); }
左右滑动的判断
这里有两种方法实现左右滑动的判断:1. 通过设置
gestureDetector.setOnDoubleTapListener(listener),在
listener中
onFing()方法根据初始位置和结束位置的位移,判断左滑还是右滑。这里注意,如果你的计算方法是:结束位置-初始位置,那么此值>0时,为右滑,<0为左滑。思路比较简单,故不贴代码。
PS:
OnGestureListener的
onScroll()方法,当手指按下屏幕并拖动的时候,会触动这个方法。那这里为什么在方法里做左右滑动判断呢?原因是这样的:每次有效的滑动,都会调用
onScroll()方法,也就是说在一个完整的
ACTION_DOWN-->ACTION_MOVE-->ACTION_UP中,
onScroll()可能会调用很多次。这会带来一些不必要的问题。而
onFing()方法的优点是,在一个完整的滑动周期中,它只会调用一次,因为它代表的是一个完整的快速滑动的行为,而
onScroll()
2. 方法1使用比较简单,但是需要我们使用
GestureDetector,并且实现
OnDoubleTapListener。如何在不使用这些的情况下,实现标题描述的需求呢?答案就是:重写目标的
onTouchEvent(XXX)。下贴代码:
@Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP){ int count = event.getPointerCount() ; float x1 = event.getX(0) ; float x2 = event.getX(count - 1); float scrollDistance = x1 - x2; if (scrollDistance > 100){ Toast.makeText(this, "左滑动", Toast.LENGTH_SHORT).show(); }else if (scrollDistance<-100){ Toast.makeText(this, "右滑动", Toast.LENGTH_SHORT).show(); }else { } } return gestureDetector.onTouchEvent(event); }
最近下眼睑肿的厉害,开了个脑洞,万一这是个病,万一这个病不能写代码,那我怎么办。 = =。
相关文章推荐
- C++ 析构函数 为何一般定义为虚函数
- 详解Python的Twisted框架中reactor事件管理器的用法
- sizeof与strlen的用法与区别
- Zookeeper注册中心安装
- JS 跳出iframe框架
- JavaScript 垃圾回收
- Jquery的问题(一)
- MySQL DEBUG_SYNC 的简单分析与测试
- 空间点
- 蓝桥杯 国王的烦恼
- Java多线程初学者指南(9):为什么要进行数据同步
- ftp自动下载shell脚本
- protobuf开发指南
- java学习总结(16.05.25)eclipse的查找和替换功能 Ctrl+F
- db2与oracle、mysql使用区别
- taobao月报 ---mysql汇总
- 用Maven插件生成Mybatis代码
- 前台模块化RequireJS+anjularJS的实战应用(一)---- 理论基础
- Oracle中sys和system用户、系统权限和角色的区别
- History API