編輯:關於 Android 程式設計
理解Touch事件的分發機制,是掌握Android UI開發的關鍵一步。本文以實例為切入點,層層深入原始碼,完整解析從使用者觸摸螢幕到最終觸發點擊事件的整個流程。
我們先從一個簡單的示例說起,佈局如下:

佈局檔:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" tools:context="com.example.touch_event.MainActivity" tools:ignore="MergeRootFrame" > <Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> </FrameLayout>
MainActivity:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button mBtn = (Button) findViewById(R.id.my_button); mBtn.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("", "### onTouch : " + event.getAction()); return false; } }); mBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("", "### onClick : " + v); } }); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d("", "### activity dispatchTouchEvent"); return super.dispatchTouchEvent(ev); } }
點擊按鈕時輸出如下Log:
08-31 03:03:56.116: D/(1560): ### activity dispatchTouchEvent 08-31 03:03:56.116: D/(1560): ### onTouch : 0 08-31 03:03:56.196: D/(1560): ### activity dispatchTouchEvent 08-31 03:03:56.196: D/(1560): ### onTouch : 1 08-31 03:03:56.196: D/(1560): ### onClick : android.widget.Button{52860d98 VFED..C. ...PH... 0,0-1080,144 #7f05003d app:id/my_button}
可以看到:先執行 Activity 的 dispatchTouchEvent,再執行 onTouch,然後再一次 dispatchTouchEvent → onTouch,最後才觸發 onClick。為什麼 dispatchTouchEvent 與 onTouch 都執行了兩次,而 onClick 只執行一次?兩次Touch事件的 action 為何是 0 和 1?
答案就在 MotionEvent 的定義中:
public final class MotionEvent extends InputEvent implements Parcelable { // 代碼省略 public static final int ACTION_DOWN = 0; // 按下事件 public static final int ACTION_UP = 1; // 抬起事件 public static final int ACTION_MOVE = 2; // 手勢移動事件 public static final int ACTION_CANCEL = 3; // 取消 // 代碼省略 }
原來按下事件為0、抬起事件為1。由於範例中只有按下與抬起、沒有移動,因此產生兩次Touch事件。
再看另外兩個場景:
1、點擊按鈕外的區域,只輸出:
08-31 03:04:45.408: D/(1560): ### activity dispatchTouchEvent08-31 03:04:45.512: D/(1560): ### activity dispatchTouchEvent
2、若 onTouch 回傳 true:
08-31 03:06:04.764: D/(1612): ### activity dispatchTouchEvent 08-31 03:06:04.764: D/(1612): ### onTouch : 0 08-31 03:06:04.868: D/(1612): ### activity dispatchTouchEvent 08-31 03:06:04.868: D/(1612): ### onTouch : 1
此時點擊事件不會觸發。要理解這些現象,就得深入事件分發的源碼。
使用者觸摸螢幕會產生觸摸訊息,最終傳送到 ViewRoot(4.2源碼中改為 ViewRootImpl)的 InputHandler。ViewRoot 是 GUI 管理系統與呈現系統之間的橋樑,它並非 View 型別,而是一個 Handler。InputHandler 用於處理 KeyEvent 與 TouchEvent:
public final class ViewRoot extends Handler implements ViewParent, View.AttachInfo.Callbacks { // 代碼省略 private final InputHandler mInputHandler = new InputHandler() { public void handleKey(KeyEvent event, Runnable finishedCallback) { startInputEvent(finishedCallback); dispatchKey(event, true); } public void handleMotion(MotionEvent event, Runnable finishedCallback) { startInputEvent(finishedCallback); dispatchMotion(event, true); // 1、handle 觸摸消息 } }; // 代碼省略 // 2、分發觸摸消息 private void dispatchMotion(MotionEvent event, boolean sendDone) { int source = event.getSource(); if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { dispatchPointer(event, sendDone); // 分發觸摸消息 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { dispatchTrackball(event, sendDone); } else { // TODO Log.v(TAG, "Dropping unsupported motion event (unimplemented): " + event); if (sendDone) { finishInputEvent(); } } } // 3、通過Handler投遞消息 private void dispatchPointer(MotionEvent event, boolean sendDone) { Message msg = obtainMessage(DISPATCH_POINTER); msg.obj = event; msg.arg1 = sendDone ? 1 : 0; sendMessageAtTime(msg, event.getEventTime()); } @Override public void handleMessage(Message msg) { // ViewRoot覆寫handlerMessage來處理各種消息 switch (msg.what) { // 代碼省略 case DO_TRAVERSAL: if (mProfile) { Debug.startMethodTracing("ViewRoot"); } performTraversals(); if (mProfile) { Debug.stopMethodTracing(); mProfile = false; } break; case DISPATCH_POINTER: { // 4、處理DISPATCH_POINTER類型的消息,即觸摸屏幕的消息 MotionEvent event = (MotionEvent) msg.obj; try { deliverPointerEvent(event); // 5、處理觸摸消息 } finally { event.recycle(); if (msg.arg1 != 0) { finishInputEvent(); } if (LOCAL_LOGV || WATCH_POINTER) Log.i(TAG, "Done dispatching!"); } } break; // 代碼省略 } // 6、真正的處理事件 private void deliverPointerEvent(MotionEvent event) { if (mTranslator != null) { mTranslator.translateEventInScreenToAppWindow(event); } boolean handled; if (mView != null && mAdded) { // enter touch mode on the down boolean isDown = event.getAction() == MotionEvent.ACTION_DOWN; if (isDown) { ensureTouchMode(true); // 如果是ACTION_DOWN事件則進入觸摸模式,否則為按鍵模式。 } if(Config.LOGV) { captureMotionLog("captureDispatchPointer", event); } if (mCurScrollY != 0) { event.offsetLocation(0, mCurScrollY); // 物理坐標向邏輯坐標的轉換 } if (MEASURE_LATENCY) { lt.sample("A Dispatching TouchEvents", System.nanoTime() - event.getEventTimeNano()); } // 7、分發事件,如果是窗口類型,則這裡的mView對應的就是PhonwWindow中的DecorView,否則為根視圖的ViewGroup。 handled = mView.dispatchTouchEvent(event); // 代碼省略 } } // 代碼省略 }
無論 mView 是 DecorView 還是非視窗的根視圖,其本質都是 ViewGroup,也就是說觸摸事件最終由根視圖 ViewGroup 進行分發。
以 Activity 為例,其 dispatchTouchEvent 實際上是呼叫 PhoneWindow 的 dispatchTouchEvent:
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { // 1、調用的是PhoneWindow的superDispatchTouchEvent(ev) return true; } return onTouchEvent(ev); } public void onUserInteraction() { }
而 PhoneWindow 又將事件交給 DecorView 處理:
@Override public boolean superDispatchTouchEvent(MotionEvent event) { return mDecor.superDispatchTouchEvent(event); }
DecorView 繼承自 FrameLayout,它將 touch 事件的分發與處理都交給父類(FrameLayout → ViewGroup)來處理:
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker { /* package */int mDefaultOpacity = PixelFormat.OPAQUE; /** The feature ID of the panel, or -1 if this is the application's DecorView */ private final int mFeatureId; private final Rect mDrawingBounds = new Rect(); private final Rect mBackgroundPadding = new Rect(); private final Rect mFramePadding = new Rect(); private final Rect mFrameOffsets = new Rect(); private boolean mChanging; private Drawable mMenuBackground; private boolean mWatchingForMenu; private int mDownY; public DecorView(Context context, int featureId) { super(context); mFeatureId = featureId; } @Override public boolean dispatchKeyEvent(KeyEvent event) { final int keyCode = event.getKeyCode(); // 代碼省略 return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event) : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { final Callback cb = getCallback(); return cb != null && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) : super .dispatchTouchEvent(ev); } @Override public boolean dispatchTrackballEvent(MotionEvent ev) { final Callback cb = getCallback(); return cb != null && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev) : super .dispatchTrackballEvent(ev); } public boolean superDispatchKeyEvent(KeyEvent event) { return super.dispatchKeyEvent(event); } public boolean superDispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); } public boolean superDispatchTrackballEvent(MotionEvent event) { return super.dispatchTrackballEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { return onInterceptTouchEvent(event); } // 代碼省略 }
繼續追蹤到 ViewGroup,它才是事件分發的核心:
/** * {@inheritDoc} */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!onFilterTouchEventForSecurity(ev)) { return false; } final int action = ev.getAction(); final float xf = ev.getX(); final float yf = ev.getY(); final float scrolledXFloat = xf + mScrollX; final float scrolledYFloat = yf + mScrollY; final Rect frame = mTempRect; boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; if (action == MotionEvent.ACTION_DOWN) { if (mMotionTarget != null) { // this is weird, we got a pen down, but we thought it was // already down! // XXX: We should probably send an ACTION_UP to the current // target. mMotionTarget = null; } // If we're disallowing intercept or if we're allowing and we didn't // intercept if (disallowIntercept || !onInterceptTouchEvent(ev)) // 1、是否禁用攔截、是否攔截事件 // reset this event's action (just to protect ourselves) ev.setAction(MotionEvent.ACTION_DOWN); // We know we want to dispatch the event down, find a child // who can handle it, start with the front-most child. final int scrolledXInt = (int) scrolledXFloat; final int scrolledYInt = (int) scrolledYFloat; final View[] children = mChildren; final int count = mChildrenCount; for (int i = count - 1; i >= 0; i--) // 2、迭代所有子view,查找觸摸事件在哪個子view的坐標范圍內 final View child = children[i]; if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { child.getHitRect(frame); // 3、獲取child的坐標范圍 if (frame.contains(scrolledXInt, scrolledYInt)) // 4、判斷發生該事件坐標是否在該child坐標范圍內 // offset the event to the view's coordinate system final float xc = scrolledXFloat - child.mLeft; final float yc = scrolledYFloat - child.mTop; ev.setLocation(xc, yc); child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; if (child.dispatchTouchEvent(ev)) // 5、child處理該事件 // Event handled, we have a target now. mMotionTarget = child; return true; } // The event didn't get handled, try the next view. // Don't reset the event's location, it's not // necessary here. } } } } } boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL); if (isUpOrCancel) { // Note, we've already copied the previous state to our local // variable, so this takes effect on the next event mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; } // The event wasn't an ACTION_DOWN, dispatch it to our target if // we have one. final View target = mMotionTarget; if (target == null) { // We don't have a target, this means we're handling the // event as a regular view. ev.setLocation(xf, yf); if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) { ev.setAction(MotionEvent.ACTION_CANCEL); mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; } return super.dispatchTouchEvent(ev); } // if have a target, see if we're allowed to and want to intercept its // events if (!disallowIntercept && onInterceptTouchEvent(ev)) { final float xc = scrolledXFloat - (float) target.mLeft; final float yc = scrolledYFloat - (float) target.mTop; mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; ev.setAction(MotionEvent.ACTION_CANCEL); ev.setLocation(xc, yc); if (!target.dispatchTouchEvent(ev)) { // target didn't handle ACTION_CANCEL. not much we can do // but they should have. } // clear the target mMotionTarget = null; // Don't dispatch this event to our own view, because we already // saw it when intercepting; we just want to give the following // event to the normal onTouchEvent(). return true; } if (isUpOrCancel) { mMotionTarget = null; } // finally offset the event to the target's coordinate system and // dispatch the event. final float xc = scrolledXFloat - (float) target.mLeft; final float yc = scrolledYFloat - (float) target.mTop; ev.setLocation(xc, yc); if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) { ev.setAction(MotionEvent.ACTION_CANCEL); target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; mMotionTarget = null; } return target.dispatchTouchEvent(ev); }
重點在註解1處的條件判斷:disallowIntercept 表示是否禁用事件攔截(預設 false,可透過 requestDisallowInterceptTouchEvent 修改),onInterceptTouchEvent 則是 ViewGroup 攔截事件的函式。若在 onInterceptTouchEvent 回傳 false,就會進入條件內部,遍歷所有子 View 找到觸摸座標所在的子 View 並交由它處理。這也是實作「ListView 滑動刪除」等功能的關鍵:在 onInterceptTouchEvent 回傳 true 攔截事件,再在 onTouchEvent 中處理相關邏輯。
若子 View 不是 ViewGroup,則直接呼叫 View 的 dispatchTouchEvent:
/** * Pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the view, false otherwise. */ public boolean dispatchTouchEvent(MotionEvent event) { if (!onFilterTouchEventForSecurity(event)) { return false; } if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && mOnTouchListener.onTouch(this, event)) { return true; } return onTouchEvent(event); }
可見,若 mOnTouchListener.onTouch 回傳 true,事件被消費,就不會執行 onTouchEvent,這正說明了前面「場景2」中點擊不觸發的原因。接著看 onTouchEvent:
/** * Implement this method to handle touch screen motion events. * * @param event The motion event. * @return True if the event was handled, false otherwise. */ public boolean onTouchEvent(MotionEvent event) { final int viewFlags = mViewFlags; if ((viewFlags & ENABLED_MASK) == DISABLED) // 1、判斷該view是否enable // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. return (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) // 2、是否是clickable或者long clickable switch (event.getAction()) { case MotionEvent.ACTION_UP: // 抬起事件 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0; if ((mPrivateFlags & PRESSED) != 0 || prepressed) { // take focus if we don't have it already and we should in // touch mode. boolean focusTaken = false; if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { focusTaken = requestFocus(); // 獲取焦點 } if (!mHasPerformedLongPress) { // This is a tap, so remove the longpress check removeLongPressCallback(); // Only perform take click actions if we were in the pressed state if (!focusTaken) { // Use a Runnable and post this rather than calling // performClick directly. This lets other visual state // of the view update before click actions start. if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) // post performClick(); // 3、點擊事件處理 } } } if (mUnsetPressedState == null) { mUnsetPressedState = new UnsetPressedState(); } if (prepressed) { mPrivateFlags |= PRESSED; refreshDrawableState(); postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!post(mUnsetPressedState)) { // If the post failed, unpress right now mUnsetPressedState.run(); } removeTapCallback(); } break; case MotionEvent.ACTION_DOWN: if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } mPrivateFlags |= PREPRESSED; mHasPerformedLongPress = false; postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); break; case MotionEvent.ACTION_CANCEL: mPrivateFlags &= ~PRESSED; refreshDrawableState(); removeTapCallback(); break; case MotionEvent.ACTION_MOVE: final int x = (int) event.getX(); final int y = (int) event.getY(); // Be lenient about moving outside of buttons int slop = mTouchSlop; if ((x < 0 - slop) || (x >= getWidth() + slop) || (y < 0 - slop) || (y >= getHeight() + slop)) { // Outside button removeTapCallback(); if ((mPrivateFlags & PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); // Need to switch from pressed to not pressed mPrivateFlags &= ~PRESSED; refreshDrawableState(); } } break; } return true; } return false; }
可見 onTouchEvent 主要處理 ACTION_DOWN、ACTION_MOVE、ACTION_UP 等事件,其中最重要的是 ACTION_UP(註解3),因為點擊事件正是在此透過 post 一個 PerformClick 物件來觸發:
/** * Causes the Runnable to be added to the message queue. * The runnable will be run on the user interface thread. * * @param action The Runnable that will be executed. * * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. */ public boolean post(Runnable action) { Handler handler; if (mAttachInfo != null) { handler = mAttachInfo.mHandler; } else { // Assume that post will succeed later ViewRoot.getRunQueue().post(action); return true; } return handler.post(action); }
而 PerformClick 內部就是包裝了 performClick():
private final class PerformClick implements Runnable { public void run() { performClick(); } }
performClick() 最終呼叫 mOnClickListener.onClick(this),也就是執行使用者透過 setOnClickListener 設定的點擊監聽器:
/** * Register a callback to be invoked when this view is clicked. If this view is not * clickable, it becomes clickable. * * @param l The callback that will run * * @see #setClickable(boolean) */ public void setOnClickListener(OnClickListener l) { if (!isClickable()) { setClickable(true); } mOnClickListener = l; } /** * Call this view's OnClickListener, if it is defined. * * @return True there was an assigned OnClickListener that was called, false * otherwise is returned. */ public boolean performClick() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); if (mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); mOnClickListener.onClick(this); return true; } return false; }
整個流程可以濃縮為:使用者觸摸螢幕產生觸摸訊息,系統底層將其轉發給 ViewRoot(ViewRootImpl),ViewRoot 產生 DISPATCH_POINTER 訊息並在 handleMessage 中透過 deliverPointerEvent 處理,最終呼叫 mView.dispatchTouchEvent 分發。由於 mView 是 ViewGroup,它會遍歷所有子 View,比對觸摸座標是否落在某子 View 範圍內,若是則交由該子 View 處理;若子 View 為 ViewGroup 則繼續遞迴,否則執行 View 的 dispatchTouchEvent。在 View 中先判斷是否 enable 與 mOnTouchListener,若 onTouch 回傳 false 才會執行 onTouchEvent 並觸發 onClick;若回傳 true 則點擊事件不會被執行。
粗略的流程圖如下:

理解這套事件分發機制,能幫助你在開發複雜互動時精準掌控事件的流向,是深入掌握Android UI的必備基礎。
selector 進階用法:CardView 的前景回饋與 GridView 選中狀態保留
selector 對 Android 開發者來說再熟悉不過:在 drawable 目錄下寫一個 xml,布局裡用 background 引用,或者在程式碼中 setBac
Android 非同步網路請求庫 android-async-http 完全解析
在 Android 上進行網路請求,一般會採用 Apache HTTP Client 或 HttpURLConnection。但直接用這兩個類別,往往得寫一大堆程式碼才能
騰訊WiFi管家怎麼連上別人分享的熱點?操作教學與法律提醒
騰訊WiFi管家和「WiFi萬能鑰匙」是同一類型的工具,本質上並不是破解加密,而是把使用者自願分享的熱點密碼集中成一份資料庫,讓手機在訊號範圍內可以一鍵連上。這也是為什麼
Android 裝置管理員漏洞剖析:為什麼木馬能讓你「無法解除安裝」
本文整理自百度安全實驗室對 Android DeviceAdmin 機制設計缺陷的公開分析,屬於防禦性安全研究,重點在於理解風險並及早防護。 背景:兩代 DeviceA