设计思路,步骤,方法
1.获取当前MotionEvent对象
2.mGestureDetector.onTouchEvent(event);利用GestureDetector对象调用onTouchEvent()方法把event对象传给GestureListener
3.继承监听器SimpleOnGestureListener 里面包含了两个接口,调用onfling()方法进行手势滑动的识别
我们先做一下准备工作
这是我们的手势识别载体,所有在这上面的手势才能识别因为在activity中设置的是miv.setOnTouchListener();
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
在activity中初始化 imageview
miv = (ImageView) findViewById(R.id.imageView1);
然后进行第一步,第二步操作
miv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
//这是第二部操作
mGestureDetector.onTouchEvent(event);
return true;
}
});
接下来进行第三步操作、
class mSimleGestureListener extends SimpleOnGestureListener{
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
if(e1.getX()-e2.getX()>50){
Toast.makeText(getApplicationContext(), "从右向左滑的手势", Toast.LENGTH_SHORT).show();
}else if(e2.getX()-e1.getX()>50){
Toast.makeText(getApplicationContext(), "从左向右滑的手势", Toast.LENGTH_SHORT).show();
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}
是否还记得GestureDetector还没初始化,因为初始化要传一个SimpleOnGestureListener对象的参数,那么在oncreate()方法里面添加
mGestureDetector = new GestureDetector(new mSimleGestureListener());
注意:整个这样的方法有缺陷,就是打一个全回到离原点没超过50像素的话,就会当作没有移动至50像素以外的地方,所以没反应。