我们可以通过实现这两个接口中的相应方法来完成对用户在屏幕上的手势运动轨迹做监听,可以实现一个简单的左右或者上下滑动来切换屏幕。总共通过3步来完成。第一步:先实现OnTouchuListener和OnGestureListener这两个接口。第二步:实例化一个GestureDetector对象,并且获取当前页面的布局对该布局设置setOnTouchListener(this)和setLongClickable(true)注意必须要同时设置这两个方法否则无法实现手势运动监听。第三步:重写这两个接口中最主要的两个方法:boolean onTouch(View v, MotionEvent event),boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)。
代码:
public class MyAcitivity2 extends Activity implements OnTouchListener,OnGestureListener{ //第一步
//第二步
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.MyActivity);
gd = new GestureDetector((OnGestureListener)this);
LinearLayout ll = (LinearLayout) findViewById(R.id.myactivitylayout);
ll.setOnTouchListener(this);
ll.setLongClickable(true);
}
//第三步:最主要的两个方法
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
if(e1.getX() - e2.getX() > FLING_MIN_DISTANCE&&Math.abs(velocityX) > FLING_MIN_VELOCITY) { //向左滑动
Intent intent = new Intent(this,MyActivity1.class);
startActivity(intent);
finish();
}
else if (e2.getX()-e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) >FLING_MIN_VELOCITY) {
//向右滑动
Intent intent = new Intent(this, Setup1Activity.class);
startActivity(intent);
finish();
}
return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gd.onTouchEvent(event);
}
}
这样就可以通过上下左右滑动来实现切换屏幕