//手勢解析工具類
private GestureDetector gesturedetector;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//慢速滑動
gesturedetector = new GestureDetector(this,new GestureDetector.SimpleOnGestureListener() {
//快速滑動
public boolean onScroll(MotionEvent e1, MotionEvent e2,float distanceX, float distanceY) {
return super.onScroll(e1, e2, distanceX, distanceY);
}
//當手勢解析器發(fā)現(xiàn)手指在屏幕快速滑動時調(diào)用此方法
//@param e1 down事件時的MotionEvent
//@param e2 最近一個move事件時的MotionEvent
//@param velocityX X方向的移動速度
//@param velocityY Y方向的移動速度
public boolean onFling (MotionEvent e1 , MotionEvent e2,float velocityX ,float velocityY) {
//速度太慢 不做處理
if(Math.abs(velocityX)<200){
return true;
}
//向左滑 速度為負數(shù),相當于點擊下一步
//向右滑 速度為正數(shù),相當于點擊上一步
if(e1.getX()>e2.getX()){ //向左滑
toNext(null);
//這里的參數(shù)null是因為在事件監(jiān)聽的地方?jīng)]有使用view所以不會發(fā)生空指針異常
}
else{ //向右滑
toPrevious(null);
//這里的null同上
}
return super.onFling(e1,e2,velocityX,velocityY);
}
});
}
//重寫該方法,獲得用戶在屏幕上的觸摸事件
//手指按下時,發(fā)生down事件
//手指移動時,短時間內(nèi)發(fā)生大量move事件
//手指抬起時,發(fā)生up事件
public boolean onTouchEvent(MotionEvent event){
//將事件交給手勢解析工具類 由gesturedetector來解析手勢
gesturedetector.onTouchEvent(event);
return true;
}
//響應上一步的點擊事件
public void toPrevious(View v){
pre();
overridePendingTransition(R.anim.pret_in, R.anim.pre_out);
}
public abstract void pre();
//響應下一步的點擊事件
public void toNext(View v){
//切換到下一個頁面
next();
//執(zhí)行切換下一個頁面的動畫
overridePendingTransition(R.anim.next_in, R.anim.next_out);
}
public abstract void next();