android事件分發的理解

android事件分發

基本概念

  • touch事件定義

    什麼是Touch事件?java

    一個Touch事件在用戶點擊屏幕(ACTION_DOWN)時產生,擡起手指(ACTION_UP)時結束,而Touch事件又被封裝到MotionEvent當中。android

  • 事件分類

    touch事件能夠分爲如下:安全

    事件類型 說明
    ACTION_DOWN 手指按下
    ACTION_MOVE 手指移動
    ACTION_UP 手指擡起
    ACTION_POINTER_DOWN 多手指按下
    ACTION_POINTER_UP 多手指擡起
    ACTION_CANCEL 取消事件

    獲取事件類型的Action方式最多見的是經過MotionEvent的getAction()方法,getAction()方法能夠獲ACTION_DONW、ACTION_UP、ACTION_MOVE、以及ACTION_CANCEL等事件,咱們分析事件傳遞時基本也是分析這些事件。app

    ACTION_POINTER_DOWN和ACTION_POINTER_UP,則得和ACTION_MASK相與才能獲得。ide

  • 事件順序

  • 事件傳遞層級

View事件分發流程

  • 實例分析

...源碼分析

class TestView : View {
companion object {
    val TAG: String = TestView::class.java.simpleName
}

constructor(context: Context) : super(context) {

}

constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {

}

override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
    Log.d(TAG, "TestView dispatchTouchEvent-------------------------")
    return super.dispatchTouchEvent(event)
}

override fun onTouchEvent(event: MotionEvent?): Boolean {
    Log.d(TAG, "TestView onTouchEvent-------------------------")
    return super.onTouchEvent(event)
    }
   }
複製代碼

...ui

...this

class MainActivity : AppCompatActivity() {
companion object {
    val TAG: String = MainActivity::class.java.simpleName
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    testView.setOnTouchListener(object : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            Log.d(TAG, "onTouch ----------------------")
            return false
        }
    })
}
  }
複製代碼

...spa

當我手指觸摸屏幕移動擡起來的時候,後臺日誌輸出rest

...

2019-05-16 14:45:35.601 19010-19010/com.example.alldemo D/TestView: TestView    dispatchTouchEvent-------------------------
 2019-05-16 14:45:35.602 19010-19010/com.example.alldemo D/MainActivity: onTouch ----------------------
 2019-05-16 14:45:35.602 19010-19010/com.example.alldemo D/TestView: TestView onTouchEvent-------------------------
複製代碼

...

能夠看到調用順序是View.dispatchTouchEvent -> onTouch -> View.onTouchEvent

若是此時我這樣設置

...

class MainActivity : AppCompatActivity() {
companion object {
    val TAG: String = MainActivity::class.java.simpleName
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    testView.setOnTouchListener(object : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            Log.d(TAG, "onTouch ----------------------")
            return true
        }
    })
}
 }
複製代碼

...

直接在setOnTouchListener的回調中return true的時候,此時後臺日志

...

2019-05-16 14:56:25.081 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.082 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.095 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.095 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.105 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.105 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.121 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.122 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.139 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.139 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
複製代碼

...

此時調用順序是View.dispatchTouchEvent -> onTouch View.onTouchEvent再也不執行

  • 源碼分析

    下面經過源碼分析View的事件分發流程吧,從日誌看,View的事件分發流程開啓都是在是View.dispatchTouchEvent裏面

...

public boolean dispatchTouchEvent(MotionEvent event) {
    // If the event should be handled by accessibility focus first.
    //事件分發前進行的檢查,不是本人研究的重點,直接跳過
    if (event.isTargetAccessibilityFocus()) {
        // We don't have focus or no virtual descendant has it, do not handle the event.
        if (!isAccessibilityFocusedViewOrHost()) {
            return false;
        }
        // We have focus and got the event, then use normal event dispatch.
        event.setTargetAccessibilityFocus(false);
    }

    boolean result = false;//使用標誌位

    if (mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onTouchEvent(event, 0);
    }

    final int actionMasked = event.getActionMasked();
    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Defensive cleanup for new gesture
        stopNestedScroll();
    }

    if (onFilterTouchEventForSecurity(event)) {
        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
            result = true;
        }
        //noinspection SimplifiableIfStatement
        ListenerInfo li = mListenerInfo;
        //mOnTouchListener就是例子中設置進去的OnTouchListener
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED
                && li.mOnTouchListener.onTouch(this, event)) {//返回true的話,直接設置 result = true
            result = true;
        }
       
         //若是result = true的話,那麼!result就不成立,直接跳出來,也就是不在執行onTouchEvent了
        if (!result && onTouchEvent(event)) {
            result = true;
        }
    }

    if (!result && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
    }

    // Clean up after nested scrolls if this is the end of a gesture;
    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
    // of the gesture.
    if (actionMasked == MotionEvent.ACTION_UP ||
            actionMasked == MotionEvent.ACTION_CANCEL ||
            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
        stopNestedScroll();
    }

    return result;
}
複製代碼

...

從代碼看View執行的分發流程仍是比較簡單的,代碼量也很少,下面總結一下View的事件分發流程

  • View的事件分發流程

ViewGroup事件分發流程

  • 實例分析

    自定義一個ViewGroup

'''

class TestViewGroup : LinearLayout {

    companion object {
    val TAG: String = TestViewGroup::class.java.simpleName
    }

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {

    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        Log.d(TAG, "TestViewGroup onInterceptTouchEvent------------------------- action =" + ev?.action)
        return super.onInterceptTouchEvent(ev)
    }

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        Log.d(TAG, "TestViewGroup dispatchTouchEvent------------------------- action =" + event?.action)
        return super.dispatchTouchEvent(event)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.d(TAG, "TestViewGroup onTouchEvent------------------------- action =" + event?.action)
        return super.onTouchEvent(event)
    }
}
複製代碼

'''

TestView的代碼以下

'''

class TestView : View {
    companion object {
        val TAG: String = TestView::class.java.simpleName
    }

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {

    }

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        Log.d(TAG, "TestView dispatchTouchEvent-------------------------action =" + event?.action)
        return super.dispatchTouchEvent(event)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.d(TAG, "TestView onTouchEvent-------------------------action =" + event?.action)
        return super.onTouchEvent(event)
    }
}
複製代碼

'''

Activity代碼設置以下:

'''

class MainActivity : AppCompatActivity() {
    companion object {
        val TAG: String = MainActivity::class.java.simpleName
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        testView.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                Log.d(TAG, "testView onTouch ---------------------- action =" + event?.action)
                return false
            }
        })

        testViewGroup.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                Log.d(TAG, "testViewGroup onTouch ---------------------- action =" + event?.action)
                return false
            }
        })
    }
}
複製代碼

'''

運行項目以後,用手指在屏幕觸摸一下,後臺日誌輸出以下:

'''

2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =0
2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =0
2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/TestView: TestView onTouchEvent-------------------------action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/MainActivity: testViewGroup onTouch ---------------------- action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup onTouchEvent------------------------- action =0
複製代碼

'''

若是我此時把Activity的代碼這樣改動一下:

'''

testView.setOnTouchListener(object : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            Log.d(TAG, "testView onTouch ---------------------- action =" + event?.action)
            return true
        }
    })
複製代碼

'''

手指觸摸,日誌輸出以下:

'''

2019-05-16 15:42:17.769 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =0
2019-05-16 15:42:17.769 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =0
2019-05-16 15:42:17.770 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =0
2019-05-16 15:42:17.770 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =0
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =1
複製代碼

'''

說明一下 action=0表明的事件是ACTION_DOWN,action=2表明的事件是ACTION_MOVE,action=1表明的事件是ACTION_UP,

從日誌分析,第一次默認的狀況下,事件分發是先從TestViewGroup.dispatchTouchEvent -> TestViewGroup.onInterceptTouchEvent -> TestView.dispatchTouchEvent - > testView onTouch -> TestView.onTouchEvent - > testViewGroup onTouch -> TestViewGroup.onTouchEvent

第二次,事件分發是從TestViewGroup.dispatchTouchEvent(ACTION_DOWN) -> TestViewGroup.onInterceptTouchEvent(ACTION_DOWN) ->TestView.dispatchTouchEvent(ACTION_DOWN) ->testView onTouch(ACTION_DOWN) -> TestViewGroup.dispatchTouchEvent(ACTION_MOVE) ->TestViewGroup.onInterceptTouchEvent((ACTION_MOVE)) -> TestView.dispatchTouchEvent(ACTION_MOVE) -> testView onTouch(ACTION_MOVE) -> TestViewGroup.dispatchTouchEvent(ACTION_UP) ->TestViewGroup.onInterceptTouchEvent((ACTION_UP)) -> TestView.dispatchTouchEvent(ACTION_UP) -> testView onTouch(ACTION_UP)

從方法中,ViewGroup的事件分發比View的事件分發多了onInterceptTouchEvent,下面咱們從源碼角度來理解一下ViewGroup的事件分發流程

  • ViewGroup源碼分析

    與View同樣,dispatchTouchEvent也是ViewGroup的事件分發入口

'''

@Override
   public boolean dispatchTouchEvent(MotionEvent ev) {
       if (mInputEventConsistencyVerifier != null) {
           mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
       }
          //若是事件指向一個可達的那麼正常分發
       // If the event targets the accessibility focused view and this is it, start
       // normal event dispatch. Maybe a descendant is what will handle the click.
       if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
           ev.setTargetAccessibilityFocus(false);
       }

       boolean handled = false;//是否處理的標誌
       //安全性檢查,返回true才進行
       if (onFilterTouchEventForSecurity(ev)) {
           final int action = ev.getAction();
           final int actionMasked = action & MotionEvent.ACTION_MASK;

           // Handle an initial down.
           if (actionMasked == MotionEvent.ACTION_DOWN) {
               // Throw away all previous state when starting a new touch gesture.
               // The framework may have dropped the up or cancel event for the previous gesture
               // due to an app switch, ANR, or some other state change.
               cancelAndClearTouchTargets(ev);
               resetTouchState();
           }

           // Check for interception.
           //是否intercepted的標誌,也就是前面提到的ViewGroup比View多的onInterceptTouchEvent方法標誌
           final boolean intercepted;
           //事件開始或者事件已經有target的時候都會進去,由於若是事件不是剛開始並且事件mFirstTouchTarget爲空就沒有必要判斷攔截了,默認攔截
           if (actionMasked == MotionEvent.ACTION_DOWN
                   || mFirstTouchTarget != null) {
               final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
               if (!disallowIntercept) {
                   intercepted = onInterceptTouchEvent(ev);
                   ev.setAction(action); // restore action in case it was changed
               } else {
                   intercepted = false;
               }
           } else {
               // There are no touch targets and this action is not an initial down
               // so this view group continues to intercept touches.
               intercepted = true;
           }

           // If intercepted, start normal event dispatch. Also if there is already
           // a view that is handling the gesture, do normal event dispatch.
           if (intercepted || mFirstTouchTarget != null) {
               ev.setTargetAccessibilityFocus(false);
           }

           // Check for cancelation.
           final boolean canceled = resetCancelNextUpFlag(this)
                   || actionMasked == MotionEvent.ACTION_CANCEL;

           // Update list of touch targets for pointer down, if needed.
           final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
           TouchTarget newTouchTarget = null;
           boolean alreadyDispatchedToNewTouchTarget = false;
           //事件沒有取消,而且事件沒有攔截的狀況下,去找子view,看看那個消費了此次事件
           if (!canceled && !intercepted) {

               // If the event is targeting accessibility focus we give it to the
               // view that has accessibility focus and if it does not handle it
               // we clear the flag and dispatch the event to all children as usual.
               // We are looking up the accessibility focused host to avoid keeping
               // state since these events are very rare.
               View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                       ? findChildWithAccessibilityFocus() : null;

               if (actionMasked == MotionEvent.ACTION_DOWN
                       || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                       || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                   final int actionIndex = ev.getActionIndex(); // always 0 for down
                   final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                           : TouchTarget.ALL_POINTER_IDS;

                   // Clean up earlier touch targets for this pointer id in case they
                   // have become out of sync.
                   removePointersFromTouchTargets(idBitsToAssign);

                   final int childrenCount = mChildrenCount;
                   if (newTouchTarget == null && childrenCount != 0) {
                       final float x = ev.getX(actionIndex);
                       final float y = ev.getY(actionIndex);
                       // Find a child that can receive the event.
                       // Scan children from front to back.
                       final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                       final boolean customOrder = preorderedList == null
                               && isChildrenDrawingOrderEnabled();
                       final View[] children = mChildren;
                       //安裝倒序找view這個在前面事件視圖層級有說到,事件是從內到外傳遞的
                       for (int i = childrenCount - 1; i >= 0; i--) {
                           final int childIndex = getAndVerifyPreorderedIndex(
                                   childrenCount, i, customOrder);
                           final View child = getAndVerifyPreorderedView(
                                   preorderedList, children, childIndex);

                        // If there is a view that has accessibility focus we want it
                        // to get the event first and if not handled we will perform a
                        // normal dispatch. We may do a double iteration but this is
                        // safer given the timeframe.
                        if (childWithAccessibilityFocus != null) {
                            if (childWithAccessibilityFocus != child) {
                                continue;
                            }
                            childWithAccessibilityFocus = null;
                            i = childrenCount - 1;
                        }

                        //此view有沒有佔據這次事件,沒有繼續
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }

                       //查找新的targertview,找到則跳出
                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            // Child is already receiving touch within its bounds.
                            // Give it the new pointer in addition to the ones it is handling.
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }

                        resetCancelNextUpFlag(child);
                        //遞歸的方式在子child view的子類找是否有目標view,有的話就跳出循環
                        if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                            // Child wants to receive touch within its bounds.
                            mLastTouchDownTime = ev.getDownTime();
                            if (preorderedList != null) {
                                // childIndex points into presorted list, find original index
                                for (int j = 0; j < childrenCount; j++) {
                                    if (children[childIndex] == mChildren[j]) {
                                        mLastTouchDownIndex = j;
                                        break;
                                    }
                                }
                            } else {
                                mLastTouchDownIndex = childIndex;
                            }
                            mLastTouchDownX = ev.getX();
                            mLastTouchDownY = ev.getY();
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }

                        // The accessibility focus didn't handle the event, so clear
                        // the flag and do a normal dispatch to all children.
                        ev.setTargetAccessibilityFocus(false);
                    }
                    if (preorderedList != null) preorderedList.clear();
                }

                if (newTouchTarget == null && mFirstTouchTarget != null) {
                    // Did not find a child to receive the event.
                    // Assign the pointer to the least recently added target.
                    newTouchTarget = mFirstTouchTarget;
                    while (newTouchTarget.next != null) {
                        newTouchTarget = newTouchTarget.next;
                    }
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                }
            }
        }

        // Dispatch to touch targets.
        //沒有找到目標view,那麼就是執行本身的
        if (mFirstTouchTarget == null) {
            // No touch targets so treat this as an ordinary view.
            //沒有找到目標View的時候,調用dispatchTransformedTouchEvent其實會走super.dispatchTouchEvent,因爲ViewGroup實際上是繼承View的,那麼又會走以前分析的View dispatchTouchEvent流程,最終會走到onTouchEvent
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            // Dispatch to touch targets, excluding the new touch target if we already
            // dispatched to it.  Cancel touch targets if necessary.
            TouchTarget predecessor = null;
            TouchTarget target = mFirstTouchTarget;
            while (target != null) {
                final TouchTarget next = target.next;
                //alreadyDispatchedToNewTouchTarget=true的話表示上面的view已經消費了該事件
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else {
                //繼續對子view進行事件分發
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }
                    if (cancelChild) {
                        if (predecessor == null) {
                            mFirstTouchTarget = next;
                        } else {
                            predecessor.next = next;
                        }
                        target.recycle();
                        target = next;
                        continue;
                    }
                }
                predecessor = target;
                target = next;
            }
        }

        // Update list of touch targets for pointer up or cancel, if needed.
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
    }

    if (!handled && mInputEventConsistencyVerifier != null) {
        mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
    }
    return handled;
}
複製代碼

'''

  • ViewGroup事件分發流程

相關文章
相關標籤/搜索