繼續分析DrawerLayout的手勢分發部分
談到手勢分發,這本身就是個好話題,DrawerLayout作為繼承自ViewGroup得布局他可以攔截手勢也可以分發給子view,也就是在onInterceptTouchEvent中做的操作,但是他的下面還有一個onTouchEvent方法,先看哪個呢?追溯代碼我們可以知道ViewGroup繼承自View,而onTouchEvent是View的方法
我們還是先花點時間把兩者的關係先確認再繼續。
onInterceptTouchEvent和onTouchEvent---雞和蛋?
定位到ViewGroup,可以發現onInterceptTouchEvent分定義如下,從它前面一段非常長的注釋就可以看出其重要性和複雜,預設的返回是false
/**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
onInterceptTouchEventMotionEvent ev
return false
前兩段告訴我們,複寫
onInterceptTouchEventMotionEvent ev
action MotionEventCompatev
// "|" used deliberately here; both methods should be invoked.
interceptForDrag mLeftDraggerev
action
MotionEvent
x ev
y ev
mScrimOpacity
MotionEvent
// If we cross the touch slop, don't perform the delayed peek for an edge touch.
mLeftDraggerViewDragHelper
MotionEvent
MotionEvent
interceptForDrag interceptForTap hasPeekingDrawer mChildrenCanceledTouch
傳回值,這裡有個註解說是故意用了|或,而不是||或,兩者區別在於||只要第一個條件滿足就不在執行第二個檢查,二|不同,無論如何都會將兩個條件檢查一遍;
根據條件設定當前是否滿足tap狀態,具體條件有兩個,一是,二時根據座標點的位置取得改點對應的最上層view對象,如果是預定義的content view即DrawerLayout裡的主內容展示view,也就是同時滿足view在螢幕上且點擊的位置直接落在了content view上。