手勢互動GestureDetector的教程,互動gesturedetector
GsetureDetector互動過程
- 觸屏的一刹那,觸發MotionEvent事件
- 被OnTouchListener監聽,在onTouch()中獲得MotionEvent對象
- GestureDetector轉寄MotionEvent對象到OnGestureListener
- OnGestureListener獲得該對象,根據該對象封裝的資訊做出合適的反饋
內部類:兩個監聽器介面OnGestureListener:單擊類方法
- 單擊onDown(MotionEvent e)
- 抬起onSingleTapUp(MotionEvent e)
- 短按onShowPress(MotionEvent e)
- 長按onLongPress(MotionEvent e)
- 滾動onScroll(MotionEvent e1,MotionEvent e2,float distanceX,float distanceY)
- 滑動onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY)
OnDoubleTapListener:雙擊方法
- 雙擊OnDoubleTap(MotionEvent e)
- 雙擊按下和抬起各觸發一次:onDoubleTapEvent(MotionEvent e)?應用例子?
- 單擊確定onSingleTapConfirmed(MotionEvent e)?
SimpleOnGestureListener
概述: SimpleOnGestureListener實現了上面的連個介面 OnGestureListener and OnDoubleTapListener,可以通過繼承這個類來實現你所想實現的手勢互動動作。需要的動作可以在介面裡找對應的方法,如果方法返回false就是什麼都不做。
運用例子效果
這個例子在主介面載入一個圖片,然後左右滑動提示相應的文字。
過程
- OnTouchListener監聽,在onTouch中獲得MotionEvent對象
img.setOnTouchListener(new OnTouchListener() {@Override//捕獲的觸控螢幕發生的event事件public boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubreturn true;//記得這裡改為ture}});
- 在Activity建立一個繼承於SimpleOnGestureListener的類
class MyGestureListener extends SimpleOnGestureListener{ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub //e1和e2分別是開始和結束的動作對象 //通過e1和e2位置的比較判斷手勢的動作 if (e1.getX() - e2.getX() > 50) { Toast.makeText(MainActivity.this, "從右向左滑動",0).show();}else if(e2.getX() - e1.getX() >50){ Toast.makeText(MainActivity.this, "從左向右滑動",0).show();} return super.onFling(e1, e2, velocityX, velocityY); } }
3.獲得一個GestureDetextor對象(聲明省略了)
gestureDetector = new GestureDetector(MainActivity.this, new MyGestureListener());
4.在onTouch方法中gestureDetector轉寄MotionEvent對象到OnGestureListener(這裡是MyGestureListener)
gestureDetector.onTouchEvent(event);
5.MyGestureListener獲得該對象,根據該對象封裝的資訊做出合適的反饋(左右滑動提示對應的文字)