public class TestGestureDetectorView extends LinearLayout { public static final String TAG = TestGestureDetectorView.class.getSimpleName() + "----"; public static final int ACTION_DOWN = 0; public static final int ACTION_UP = 1; public static final int ACTION_MOVE = 2; public TestGestureDetectorView(Context context, AttributeSet attrs) { super(context, attrs); init(); } GestureDetector gestureDetector; public void init() { gestureDetector = new GestureDetector(getContext(), onGestureListener); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { gestureDetector.onTouchEvent(motionEvent); return true; //請注意這裏要返回true(注:由於事件消費的緣由若是你在自定義控件爲LinearLayout默認沒有消費事件的(返回的false),那麼onScroll事件就不能執行當爲Button的時候要執行) //(因此返回true表明咱們消費了down事件,之後的事件onMove onUp處理都會在這裏處理) } }); } GestureDetector.OnGestureListener onGestureListener = new GestureDetector.OnGestureListener() { @Override public boolean onDown(MotionEvent motionEvent) { Log.e(TAG, TAG + "onDown---" + "motionEvent=" + getAction(motionEvent)); return true; } @Override public void onShowPress(MotionEvent motionEvent) { Log.e(TAG, TAG + "onShowPress---" + "motionEvent=" + getAction(motionEvent)); } @Override public boolean onSingleTapUp(MotionEvent motionEvent) { Log.e(TAG, TAG + "onSingleTapUp---" + "motionEvent=" + getAction(motionEvent)); return false; } @Override public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { Log.e(TAG, TAG + "onScroll---" + "motionEvent=" + getAction(motionEvent) + "---motionEvent1=" + getAction(motionEvent1)); return false; } @Override public void onLongPress(MotionEvent motionEvent) { Log.e(TAG, TAG + "onLongPress---" + "motionEvent=" + getAction(motionEvent)); } @Override public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { Log.e(TAG, TAG + "onFling---" + "motionEvent=" + getAction(motionEvent) + "---motionEvent1=" + getAction(motionEvent1)); return false; } }; public String getAction(MotionEvent motionEvent) { String action = "noneAction"; switch (motionEvent.getAction()) { case ACTION_DOWN: action = "ACTION_DOWN"; break; case ACTION_MOVE: action = "ACTION_MOVE"; break; case ACTION_UP: action = "ACTION_UP"; break; } return action; } }
好的咱們如今來分析一下
這些事件java
觸發回調方法 onDown(ACTION_DOWN)android
注意:ide
onDown方法只會接收到ACTION_DOWN的事件code
觸發回調方法 onDown(ACTION_DOWN)----onShowPress(ACTION_DOWN)事件
注意: onShowPress方法只會接收到ACTION_DOWN的事件get
觸發回調方法 有兩種可能it
注意:io
onSingleTapUp方法只會接收到ACTION_UP的事件class
觸發回掉方法List
onDown(ACTION_DOWN)----onShowPress(ACTION_DOWN)---onLongPress(ACTION_DOWN)
注意:
onLongPress方法只會接收到ACTION_DOWN的事件
觸發回掉方法有兩中可能
注意: