主要原理为监控触屏事件和手势事件,在触屏事件处理函数中调用手势事件处理函数,表示用户触屏后是否有手势操作,有则进行手势事件处理,大致分为四步
1、需要继承OnGestureListener和OnDoubleTapListener,如下:
2、在添加mGestureDetector的定义,并在ViewSnsActivity的onCreate函数中加入其页面布局的setOnTouchListener事件
- GestureDetector mGestureDetector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_sns_activity);
mGestureDetector = new GestureDetector((OnGestureListener) this);
LinearLayout viewSnsLayout = (LinearLayout)findViewById(R.id.viewSnsLayout);
viewSnsLayout.setOnTouchListener(this);
viewSnsLayout.setLongClickable(true);
}
mGestureDetector为手势监听对象,下面的OnFling就是为其实现,用来处理手势的
viewSnsLayout.setOnTouchListener(this);表示viewSnsLayout这个layout的触屏事件由下面的OnTouch处理
3、重载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为向量垂直方向的速度
- if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity)
则上面的语句能知道啥意思了吧,就是说向量的水平长度必须大于verticalMinDistance,并且水平方向速度大于minVelocity
从而我们可以如此判断手势是否满足一定的条件从而进行相应响应,也可以根据这个写出更复杂的手势判断。
4、重载onTouch函数
在2中我们定义了viewSnsLayout的touch事件处理,下面我们来实现,直接调用手势的处理函数
- public boolean onTouch(View v, MotionEvent event) {
- return mGestureDetector.onTouchEvent(event);
- }
查看GestureDetector类的onTouchEvent的源码就能知道,进入该函数后会进入case MotionEvent.ACTION_UP这个路径,从而调用onFling函数
如果需要设置activity切换效果,在startActivity(intent);之后添加
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);即可,可修改相应参数,可参考http://www.iteye.com/topic/1116472
其他:
关于activity添加ScrollView后或是外部为RelativeLayout时onFling不起作用,无法滑动问题见http://trinea.iteye.com/blog/1213815