android 手势处理
2011-10-28 13:40 刘XX 阅读(633) 评论(0) 收藏 举报手机已经进入了触摸屏时代,通过各式各样的手势可以让程序更加多样化,那么我们就一起来看看其工作原理:
1、需要继承OnGestureListener和OnDoubleTapListener,如下:
public class MainActivity extends Activity implements OnTouchListener,OnGestureListener{
......................................
}
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函数
private int verticalMinDistance = 20;
private int minVelocity = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (e1.getX() - e2.getX() > verticalMinDistance
&& Math.abs(velocityX) > minVelocity) {
//向左滑
}
} else if (e2.getX() - e1.getX() > verticalMinDistance
&& Math.abs(velocityX) > minVelocity) {
//向右滑
}
return false;
}
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函数
相关资料:http://trinea.iteye.com/blog/1054786
浙公网安备 33010602011771号