android-----事件分發(fā)機(jī)制測(cè)試系列
來(lái)源:程序員人生 發(fā)布時(shí)間:2016-07-18 08:29:51 閱讀次數(shù):2612次
先來(lái)講說(shuō)我遇到的問(wèn)題,這次測(cè)試使用的布局文件是:
<com.hzw.eventtest.MyRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.hzw.eventtest.MyLinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.hzw.eventtest.MyButton
android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我的按鈕" />
</com.hzw.eventtest.MyLinearLayout>
</com.hzw.eventtest.MyRelativeLayout>
也就是說(shuō)布局圖是醬紫的:

具體就是我在MyRelativeLayout中攔截了MOVE事件,在MyLinearLayout中攔截并且消費(fèi)了DOWN事件,也就是說(shuō)我僅僅修改了MyRelativeLayout$onInterceptTouchEvent中case條件為MOVE的部份和MyLinearLayout$onInterceptTouchEvent中case條件為DOWN的部份和MyLinearLayout$onTouchEvent中case條件為DOWN的部份;
具體測(cè)試代碼:點(diǎn)擊下載
最后查看Logcat輸出:
06⑵8 09:09:25.237: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.237: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.237: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.237: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_DOWN--->false
06⑵8 09:09:25.237: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.237: I/System.out(1643): MyLinearLayout--->onInterceptTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.237: I/System.out(1643): MyLinearLayout--->onInterceptTouchEvent--->ACTION_DOWN--->true
06⑵8 09:09:25.246: I/System.out(1643): MyLinearLayout--->onTouchEvent--->ACTION_DOWN
06⑵8 09:09:25.246: I/System.out(1643): MyLinearLayout--->onTouchEvent--->ACTION_DOWN--->true
06⑵8 09:09:25.246: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_DOWN--->true
06⑵8 09:09:25.246: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_DOWN--->true
06⑵8 09:09:25.246: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_DOWN--->true
06⑵8 09:09:25.326: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.326: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.326: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.326: I/System.out(1643): MyRelativeLayout--->onInterceptTouchEvent--->ACTION_MOVE--->true
06⑵8 09:09:25.326: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_CANCEL
06⑵8 09:09:25.326: I/System.out(1643): MyLinearLayout--->dispatchTouchEvent--->ACTION_CANCEL--->false
06⑵8 09:09:25.326: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.326: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.326: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.326: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.336: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.336: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.336: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.336: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.336: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.336: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE
06⑵8 09:09:25.336: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.336: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_MOVE--->false
06⑵8 09:09:25.412: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_UP
06⑵8 09:09:25.416: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_UP
06⑵8 09:09:25.416: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_UP
06⑵8 09:09:25.416: I/System.out(1643): MyRelativeLayout--->onTouchEvent--->ACTION_UP--->false
06⑵8 09:09:25.416: I/System.out(1643): MyRelativeLayout--->dispatchTouchEvent--->ACTION_UP--->false
06⑵8 09:09:25.416: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_UP
06⑵8 09:09:25.416: I/System.out(1643): MainActivity--->onTouchEvent--->ACTION_UP--->false
06⑵8 09:09:25.416: I/System.out(1643): MainActivity--->dispatchTouchEvent--->ACTION_UP--->false
下面我們來(lái)分析下具體的輸出進(jìn)程
為了便于分析,先來(lái)貼出此測(cè)試進(jìn)程中用到的部份源碼:
ViewGroup$dispatchTouchEvent
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = 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) {
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;
}
// 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;
if (!canceled && !intercepted) {
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 View[] children = mChildren;
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder ?
getChildDrawingOrder(childrenCount, i) : i;
final View child = children[childIndex];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
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);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = childIndex;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
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.
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;
}
ViewGroup$dispatchTransformedTouchEvent
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;
}
具體分析進(jìn)程:
注意:分發(fā)順序是:Activity----->ViewGroup----->View
消費(fèi)順序是:View------>ViewGroup----->Activity
View中的事件方法履行流程是:dispatchTouchEvent----->onTouchEvent
ViewGroup中的事件方法履行流程是:dispatchTouchEvent----->onInterceptTouchEvent----->onTouchEvent
(1)先來(lái)看DOWN事件部份:
事件首先傳遞到MainActivity,調(diào)用它的dispatchTouchEvent分發(fā)到他的子View(MyRelativeLayout上),由于是DOWN事件,滿足ViewGroup$dispatchTouchEvent源碼的第23行if語(yǔ)句的第1個(gè)條件,進(jìn)入if語(yǔ)句塊中,由于我們并沒(méi)有調(diào)用requestDisallowInterceptTouchEvent來(lái)干預(yù)事件的分發(fā)進(jìn)程,所以會(huì)履行第27行的onInterceptTouchEvent方法,我們的測(cè)試中MyRelativeLayout沒(méi)有攔截DOWN事件,因此該方法默許返回值是false賦給intercepted,所以你有了Logcat第4行的輸出,接著履行第46行,滿足if語(yǔ)句條件,進(jìn)入if語(yǔ)句塊中,這個(gè)里面比較關(guān)鍵的代碼是第85行的dispatchTransformedTouchEvent方法,這個(gè)方法會(huì)遞歸的處應(yīng)當(dāng)前View的子View,所以你會(huì)發(fā)現(xiàn)Logcat第11行MyRelativeLayout的dispatchTouchEvent方法才算真正結(jié)束,這里只需要知道第91行會(huì)調(diào)用addTouchTarget方法,該方法會(huì)在其子View的分發(fā)事件(dispatchTouchEvent)返回true的情況下履行,在它里面會(huì)給mFirstTouchTarget賦值便可,由于MyRelativeLayout子View是MyLinearLayout,所以履行MyLinearLayout的dispatchTouchEvent方法,接著履行MyLinearLayout的onInterceptTouchEvent方法,由于MyLinearLayout攔截了DOWN事件,因此onInterceptTouchEvent返回true,那末這時(shí)候候ViewGroup$dispatchTouchEvent的第46--⑴08行代碼將不再履行,由于此時(shí)mFirstTouchTarget還是null的,所以會(huì)履行第111行的if語(yǔ)句塊,調(diào)用dispatchTransformedTouchEvent方法,傳入的第3個(gè)參數(shù)是null,查看ViewGroup$dispatchTransformedTouchEvent源碼的第11行,發(fā)現(xiàn)他會(huì)履行super的dispatchTouchEvent方法,由于我們沒(méi)有為MyLinearLayout設(shè)置onTouch監(jiān)聽(tīng)事件,所以他直接履行了onTouchEvent方法,并且我們消費(fèi)了這個(gè)DOWN事件,所以有了Logcat第9行的輸出,接下來(lái)就是遞歸返回進(jìn)程了,即Logcat第10-⑴2行的輸出部份;
(2)接下來(lái)分析第1次MOVE事件
和上面1樣,事件首先到了MainActivity,調(diào)用他的dispatchTouchEvent方法進(jìn)行分發(fā),接著事件分發(fā)到了MyRelativeLayout上面,調(diào)用他的dispatchTouchEvent方法,由于第1次DOWN事件中,我們已將mFirstTouchTarget的值設(shè)置為非null,所以ViewGroup$dispatchTouchEvent方法走到第23行的時(shí)候依然滿足if判斷條件,履行第27行的onInterceptTouchEvent方法,所以有了第15行的Logcat輸出,由于我們?cè)?span style="font-size:14px">MyRelativeLayout中攔截了MOVE事件,所以intercepted的值將會(huì)被賦值為true,因此ViewGroup$dispatchTouchEvent的第46-⑴08行的代碼將不會(huì)履行,到了第111行判斷mFirstTouchTarget不為null,履行else語(yǔ)句部份,這里比較關(guān)鍵的在于第125行,由于此時(shí)的intercepted值為true,所以cancelChild值將為true,在履行第127行dispatchTransformedTouchEvent的時(shí)候?qū)?span style="font-size:14px">cancelChild值傳入,查看ViewGroup$dispatchTransformedTouchEvent的源碼第9行,你會(huì)發(fā)現(xiàn)他履行了ACTION_CANCEL,所以出現(xiàn)了我們Logcat輸出的第17/18行,因此第127行的if條件內(nèi)容將為false,所以handled的值此時(shí)依然是false,由于cancelChild值是true,所以履行第131行,并且此時(shí)的predecessor等于null,因此修改mFirstTouchTarget的值為next,這里就比較重要了,此處的next是null,為何呢?由于之前mFirstTouchTarget的值是MyLinearLayout,雖然MyLinearLayout有子View(MyButton),但是MyLinearLayout把DOWN時(shí)間消費(fèi)了,所以MyButton根本就沒(méi)有加入到事件處理的鏈表中,所以對(duì)mFirstTouchTarget的值進(jìn)行了修改,ViewGroup$dispatchTouchEvent的第148-⑴61行不再會(huì)修改handled的值,那末我們可以認(rèn)為MyRelativeLayout的dispatchTouchEvent方法履行結(jié)束,由于此時(shí)事件還沒(méi)有被消費(fèi),那末只能由MainActivity來(lái)進(jìn)行處理了,所以有了Logcat第20-⑵2行的輸出;
(3)接下來(lái)分析第2次以后的MOVE事件
一樣事件首先由MainActivity的dispatchTouchEvent分發(fā)到MyRelativeLayout上,履行他的dispatchTouchEvent方法,這時(shí)候候判斷ViewGroup$dispatchTouchEvent第23行的if語(yǔ)句部份,發(fā)現(xiàn)部門組條件,那末會(huì)履行第35行的else語(yǔ)句部份,設(shè)置intercepted的值為true,一樣的不會(huì)履行第46-⑴08行部份,在判斷第111行的mFirstTouchTarget是不是為null時(shí),滿足條件,履行dispatchTransformedTouchEvent方法,傳入的第3個(gè)參數(shù)是null,那末會(huì)履行super的dispatchTouchEvent方法,這屬于View的事件分發(fā)進(jìn)程,一樣我們沒(méi)有為MyRelativeLayout設(shè)置onTouch方法,所以他會(huì)直接履行onTouchEvent方法,所以有了Logcat第25行的輸出,接下來(lái)在onTouchEvent履行結(jié)束以后返回false,由于我們沒(méi)有在MyRelativeLayout中消費(fèi)MOVE事件,由于該事件沒(méi)有處理完,因此會(huì)回傳給MainActivity來(lái)進(jìn)行處理;
(4)接下來(lái)就是UP事件了:
UP事件的分析和第2次以后的MOVE事件進(jìn)程1致,就不再贅述了;
從上面的分析中,我們可以得出結(jié)論:
某1個(gè)View1旦決定攔截,那末這個(gè)事件序列以后的部份只能由他來(lái)處理,條件條件是以后的事件是可以到達(dá)該View的,就像上面的例子,DOWN事件是由MyLinearLayout來(lái)攔截消費(fèi)的,但是MOVE事件卻不是他處理的,緣由在于MyRelativeLayout對(duì)MOVE事件進(jìn)行了攔截,事件根本就不會(huì)到達(dá)MyLinearLayout;
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)