綜述
Android事件的分發從Activity的dispatchTouchEvent開始一路追進入如下:
事件傳遞分析:
1、從TestActivity的dispatchTouchEvent開始,如果調用super.dispatchTouchEvent(ev),則事件繼續向下傳遞,如果直接返回true或者false,則事件消費掉不再向下傳遞。
2、TestActivity的dispatchTouchEvent調用super.dispatchTouchEvent(ev)則會進入到Activity的dispatchTouchEvent方法中,代碼如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
//此處檢驗爲按下事件,按下事件爲事件的開始
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//此方法爲空方法 在activity在分發各種事件的時候會調用該方法
onUserInteraction();
}
//核心在此處
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
核心就在於getWindow().superDispatchTouchEvent(ev),如果此處返回true,則不會調用Activity的onTouchEvent,反之,則代表內部沒有消費事件,則傳到Activity的onTouchEvent方法中。
3、getWindow()獲取到的Window對象實際爲PhoneWindow對象,調用到PhoneWindow對象的superDispatchTouchEvent方法,代碼如下:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
//直接調用DecorView的方法
return mDecor.superDispatchTouchEvent(event);
}
此處實際直接調用了DecorView的superDispatchTouchEvent方法,進入DecorView的superDispatchTouchEvent方法,代碼如下:
public boolean superDispatchTouchEvent(MotionEvent event) {
//直接調用super方法
return super.dispatchTouchEvent(event);
}
DecorView繼承自FrameLayout,super實際調用到了ViewGroup的dispatchTouchEvent方法。
到此事件傳遞到了ViewGroup,後面開始了正式的事件分發流程
ViewGroup的事件分發
綜述:ViewGroup的事件分發實際上主要做了三件事情:
- 判斷事件是否需要攔截(註釋1)
- 找到分發的View(真正交互的View)(註釋2)
- 分發事件到View上(註釋3)
代碼如下:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
...
省略部分代碼
...
boolean handled = false;
//安全校驗 安全策略 不在頂部或被遮擋不響應 不符合安全策略方法直接返回false
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.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {//mFirstTouchTarget != null 當前已經存在處理事件的子View
//判斷是否允許攔截事件
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//允許攔截則調用onInterceptTouchEvent方法 [註釋1,後續分析]
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
//不是按下事件並且當前不存在處理事件的子View 則事件直接攔截
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
...
省略部分代碼
...
//沒有取消也沒有攔截 則去找真實交互的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);
//獲取View
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是否是處理事件的View 觸摸點是否在View的範圍之內
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
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);
//此處進行事件的分發 方法dispatchTransformedTouchEvent [註釋2]
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;
}
}
}
//分發事件到具體的目標View [註釋3]
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
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;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
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;
}
註釋1:onInterceptTouchEvent
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
進行判斷的攔截
默認的判斷條件如下:
鼠標點擊輸入 && 按下事件 && 按下鼠標左鍵 && 在滾動條的上面 返回true則攔截事件,
否則返回false則不進行攔截
註釋2:dispatchTransformedTouchEvent 進行事件的分發 返回true則說明已經找到了消費事件的子View
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
註釋3 此處進行事件的具體分發,如果有目標View子View則進行相關的分發,
否則則調用dispatchTransformedTouchEvent傳入的child爲null,
在註釋2中會調用到 super.dispatchTouchEvent(event),此時調用了View的 super.dispatchTouchEvent(event),進行相關事件的處理
View的事件分發
綜述:View的dispatchTouchEvent操作比ViewGroup簡單了許多,主要就是相關的監聽器處理【註釋1】及onTouchEvent處理邏輯【註釋2】
源碼如下:
public boolean dispatchTouchEvent(MotionEvent event) {
...
省略部分驗證相關代碼
...
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;
}
//listener相關驗證 如果設置了監聽器相關 則事件在此處消費 直接在監聽器中處理 [註釋1]
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//如果result仍然爲false 則表示無監聽相關處理 進入onTouchEvent相關的邏輯處理 [註釋2]
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的onTouchEvent進行相關的事件處理。
總結:
1)事件的默認傳遞流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyView:dispatchTouchEvent -> MyView:onTouchEvent ->MyViewGroup:onTouchEvent ->
TestActivity:onTouchEvent
2) 同一個事件序列,如果子View(ViewGroup)沒有處理該事件(沒有消費事件),
那麼後續事件就不會傳遞到子View中
TestActivity:dispatchTouchEvent -> TestActivity:onTouchEvent
3)如果MyView的onTouchEvent返回了true 消費了事件 則傳遞如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyView:dispatchTouchEvent -> MyView:onTouchEvent
4)如果MyViewGroup的onInterceptTouchEvent 返回爲true,MyViewGroup的onTouchEvent返回爲false,未消費事件 則事件的傳遞流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyViewGroup:onTouchEvent -> TestActivity:onTouchEvent
5)如果MyViewGroup的onInterceptTouchEvent 返回爲true,MyViewGroup的onTouchEvent返回爲true,消費了費事件 則事件的傳遞流程如下:
TestActivity:dispatchTouchEvent -> MyViewGroup:dispatchTouchEvent ->MyViewGroup:onInterceptTouchEvent ->
MyViewGroup:onTouchEvent