对于activity或view触措事件,使用getActionMasked() 获得纯粹的事件类型,而不包含Pointer信
public class MainActivity extends Activity {
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL) :
Log.d(DEBUG_TAG,"Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
}
如果继承一个类,可重写onTouchEvent方法,而如果不想继承生成新的类,可以使用setOnTouchListener
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// ... Respond to touch events
return true;
}
});
如果要识别一个手势是长按,双击,滑动等,应当使用 GestureDetector 进行手势识别,GestureDetector类对外提供了两个接口:OnGestureListener,OnDoubleTapListener,还有一个内部类SimpleOnGestureListener;SimpleOnGestureListener类是GestureDetector提供给我们的一个更方便的响应不同手势的类,它实现了上述两个接口,该类是static class,也就是说它实际上是一个外部类,我们可以在外部继承这个类,重写里面的手势处理方法。因此实现手势识别有两种方法,一种实现OnGestureListener接口,另一种是使用SimpleOnGestureListener类
OnGestureListener有下面的几个动作
按下(onDown): 刚刚手指接触到触摸屏的那一刹那,MotionEvent.ACTION_DOWN事件
抛掷(onFling): 手指在触摸屏上迅速移动,并松开的动作。
长按(onLongPress): 手指按下持续一段时间,并且没有松开。
滚动(onScroll): 手指在触摸屏上滑动。
按住(onShowPress): 手指按在触摸屏上,它的时间范围在按下起效,在长按之前,一般用来给按下设置视觉效果
抬起(onSingleTapUp):手指离开触摸屏的那一刹那,是针对onDown事件的,onLongPress结束是不会执行这个方法的。
单击(onSingleTapConfirmed):一次tap结束,并且没有紧跟双击事件,ACTION_UP时触发
双击(onDoubleTap):发生了双击事件
双击过程中的事件(onDoubleTapEvent):双击事件中,发生的事件,包括ACTION_DOWN, ACTION_MOVE, ACTION_UP
相关函数
abstract boolean onDown(MotionEvent e)
//只要是ACTION_DOWN一定会触发,并且ACTION_DOWN后立即触发
abstract void onShowPress(MotionEvent e)
//按下了,但还没有移动,也没有ACTION_UP,一般用来提供按下的视觉反馈
abstract boolean onSingleTapUp(MotionEvent e)
//一个tap的ACTION_UP事件,onLongPress结束是不会执行这个方法的
abstract void onLongPress(MotionEvent e)
//触发了长按事件
abstract boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
//Touch了滑动一点距离后,up时触发
abstract boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
//按下并发生了滑动发生
boolean onSingleTapConfirmed(MotionEvent e)
//一次tap的ACTION_UP,并且确定没有紧跟双击事件,有点类似onClickListener
boolean onDoubleTap(MotionEvent e)
//发生了双击事件,并且e为双击事件的第一个tap的ACTION_DOWN事件
boolean onDoubleTapEvent(MotionEvent e)
//双击事件中,发生的事件,包括ACTION_DOWN, ACTION_MOVE, ACTION_UP
使用GestureDetector注意点
如果对view使用,则View必须设置longClickable为true,否则手势识别无法正确工作
如果在onTouchEvent中合用手势识别,必须 调用super对应的函数
@Override
public boolean onTouchEvent(MotionEvent event){
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}