您的位置:首页 > 其它

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);
}


最近下眼睑肿的厉害,开了个脑洞,万一这是个病,万一这个病不能写代码,那我怎么办。 = =。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: