導(dǎo)語(yǔ):
在我們使用Android做一些控件的滑動(dòng)和點(diǎn)擊時(shí)巡李,各種沖突事件、點(diǎn)擊事件無(wú)響應(yīng)等一些touch事件無(wú)響應(yīng)困擾著我們贫导,今天我將從源碼角度分析android的事件分發(fā)機(jī)制
1.簡(jiǎn)單看下例子(搞清楚onTouch和onClick的關(guān)系):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testViewGroup =(TestViewGroup)findViewById(R.id.testViewGroup);
testViewGroup.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG,"MainActivity +++ onTouch");
return true;
}
});
testViewGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"MainActivity +++ onClick");
}
});
}
當(dāng)onTouch返回值為true和false兩種不同的情況
請(qǐng)想下輸出的onTouch事件還有onClick事件的打印結(jié)果滞时?
當(dāng)為true,結(jié)果為:
當(dāng)為false捕捂,結(jié)果為:
看到這里是否有疑問(wèn)?接下來(lái)帶大家一步一步分析:
首先點(diǎn)開(kāi)View.java文件 找到: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);
}
//關(guān)鍵值斗搞,用于判斷onTouchEvent()是否該執(zhí)行
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;
}
//判斷onTouch返回值是否為true,如果為true慷妙,resulet也為true
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//為true 不執(zhí)行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;
}
li.mOnTouchListener中存放的是該View的onTouch監(jiān)聽(tīng)僻焚,所以onTouch返回true時(shí), result = true; 不執(zhí)行onTouchEvent(event)膝擂,所以打印時(shí)沒(méi)有onTouchEvent的log日志虑啤,當(dāng)onTouch返回false時(shí),接下來(lái)進(jìn)入onTouchEvent()方法架馋,打印了onTouchEvent的log日志狞山。
接下來(lái)找到onTouchEvent()方法
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// 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)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_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 (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// 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)) {
//這里執(zhí)行onClick正真的點(diǎn)擊事件的方法
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
只要看關(guān)鍵代碼,找到 performClick()方法叉寂。
在找到performClick()方法
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
//如果監(jiān)聽(tīng)類(lèi)中的li.mOnClickListener不為空萍启,則執(zhí)行它的onClick方法
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
這里就是最后的主角登場(chǎng)了onClick()方法在這里執(zhí)行。
是不是之前的疑惑迎刃而解了屏鳍。
其實(shí)前面的打印截圖留有一絲伏筆:
再看截圖:
*點(diǎn)擊事件是怎么從MainActivity的 dispatchTouchEvent傳給TestViewGroup的dispatchTouchEvent?
*TestViewGroup的dispatchTouchEvent又是怎么傳給onInterceptEvent?
帶著疑問(wèn)我們進(jìn)入第二節(jié)勘纯。
2.觸摸事件如何傳遞:
前言:
從之前的截圖可以知道事件先從MainActivity的dispatchTouchEvent開(kāi)始的。具體為什么是從MainActivity的dispatchTouchEvent開(kāi)始這篇文章不會(huì)涉及到钓瞭,將會(huì)在以后的文章中詳細(xì)解釋驳遵。
1.MainActivity的 dispatchTouchEvent傳給TestViewGroup的dispatchTouchEvent
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i(TAG,"MainActivity +++ dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
點(diǎn)開(kāi)super.dispatchTouchEvent(ev);
將會(huì)進(jìn)入Activity的dispatchTouchEvent方法:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
我們只看getWindow().superDispatchTouchEvent(ev)方法。原來(lái)dispatchTouchEvent執(zhí)行的是getWindow().superDispatchTouchEvent(ev)山涡,這個(gè)方法是干什么的呢堤结?就是將事件傳遞給Tree View布局控件。繼續(xù)點(diǎn)進(jìn)入superDispatchTouchEvent方法發(fā)現(xiàn)只是Window抽象接口鸭丛。window的實(shí)現(xiàn)類(lèi)其實(shí)是PhoneWindow竞穷,至于為什么,有了解的朋友應(yīng)該知道系吩,不知道的朋友可以去查下来庭,下篇文章會(huì)講到。通過(guò)文件查找找到PhoneWindow的superDispatchTouchEvent()方法.
@Override
public boolean superDispatchTrackballEvent(MotionEvent event) {
return mDecor.superDispatchTrackballEvent(event);
}
發(fā)現(xiàn)它還是調(diào)用的自己的內(nèi)部類(lèi)DecorView的mDecor.superDispatchTouchEvent(event)穿挨,順便提下DecorView是整個(gè)視圖組成的根視圖月弛,繼續(xù)往下走:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
發(fā)現(xiàn)它并未有實(shí)現(xiàn)這個(gè)superDispatchTouchEvent()方法而是調(diào)用父類(lèi)的dispatchTouchEvent方法肴盏。繼續(xù)點(diǎn)進(jìn)去,發(fā)現(xiàn)直接進(jìn)入到ViewGroup的dispatchTouchEvent方法帽衙,并沒(méi)有進(jìn)入DecorView的父類(lèi)FrameLayout,而是直接拋給FrameLayout的父類(lèi)ViewGroup,所有就是將事件傳遞Tree View最近的并且實(shí)現(xiàn)了ViewGroup的控件菜皂,TestViewGroup繼承自ViewGroup,并且是最上層厉萝。
所有這里就可以解釋觸摸事件是怎么從MainActivity的 dispatchTouchEvent傳給TestViewGroup的dispatchTouchEvent恍飘。
2.分析ViewGroup的dispatchTouchEvent方法
dispatchTouchEvent做了些什么,看代碼:
@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;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.當(dāng)按下的時(shí)候
// 第一次步初始狀態(tài)
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.
//清除標(biāo)記
cancelAndClearTouchTargets(ev);
//恢復(fù)標(biāo)志位
resetTouchState();
}
// Check for interception.
//第二步判斷是否攔截
// 第二次move觸發(fā)時(shí) 壓根不會(huì)遍歷子控件
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;
}
// 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;
//在該if中做真正事件分發(fā)相關(guān)操作
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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.
//child重新排序
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
//preorderedList.get(childIndex)等價(jià)于
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 條件:clickable invisiable 點(diǎn)擊事件 不在view范圍中
* 還有正在動(dòng)畫(huà)中
*/
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
/**
* 絕對(duì)接收到事件
*/
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;
}
/**
* 真正做事件分發(fā)
* child 不為空
*/
resetCancelNextUpFlag(child);
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.
//如果被攔截谴垫,則直接進(jìn)入這里
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;
}
我們只分析重要部分章母。
首先第一步初始化狀態(tài):當(dāng)手指第一次按下的時(shí)候它會(huì)先進(jìn)入cancelAndClearTouchTargets(ev)方法
/**
* Cancels and clears all touch targets.
* 清除標(biāo)志
*/
private void cancelAndClearTouchTargets(MotionEvent event) {
if (mFirstTouchTarget != null) {
boolean syntheticEvent = false;
if (event == null) {
final long now = SystemClock.uptimeMillis();
event = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
syntheticEvent = true;
}
for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
resetCancelNextUpFlag(target.child);
dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
}
clearTouchTargets();
if (syntheticEvent) {
event.recycle();
}
}
}
你可以看到如果mFirstTouchTarget不為null的時(shí)候執(zhí)行會(huì)執(zhí)行括號(hào)里的方法,最后會(huì)執(zhí)行clearTouchTargets(),進(jìn)入clearTouchTargets()可以看到就是執(zhí)行清空操作
private void clearTouchTargets() {
TouchTarget target = mFirstTouchTarget;
//進(jìn)行while循環(huán)清除存在的target標(biāo)記
if (target != null) {
do {
TouchTarget next = target.next;
target.recycle();
target = next;
} while (target != null);
//將第一次標(biāo)記清空
mFirstTouchTarget = null;
}
}
回到dispatchTouchEvent()方法翩剪,接下來(lái)看第二方法 resetTouchState():
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
發(fā)現(xiàn)該方法中還進(jìn)行了一次clearTouchTargets()方法乳怎,防止沒(méi)有清空的標(biāo)記,之后將所有的接觸狀態(tài)制為最初始狀態(tài)前弯,準(zhǔn)備重新開(kāi)始新的事件蚪缀。
接下來(lái)第二步:判斷是否被攔截。
// Check for interception. //是否攔截
// 第二次move觸發(fā)時(shí) 壓根不會(huì)遍歷子控件
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;
}
在這塊代碼中恕出,會(huì)先判斷disallowIntercept是否為false询枚,如果為false就會(huì)進(jìn)入到攔截方法onInterceptTouchEvent(ev)
補(bǔ)充:
mGroupFlags的值可以通過(guò)requestDisallowInterceptTouchEvent()設(shè)置。如果在TestViewGroup或者其子View中設(shè)置了requestDisallowInterceptTouchEvent(true)則TestViewGroup就不會(huì)執(zhí)行onInterceptTouchEvent()方法
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
// We're already in this state, assume our ancestors are too
return;
}
if (disallowIntercept) {
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}
// Pass it up to our parent
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
接下來(lái)繼續(xù)分析:disallowIntercept為false 則會(huì)進(jìn)入onInterceptTouchEvent()方法浙巫。onInterceptTouchEvent()方法我們?cè)赥estViewGroup中重寫(xiě)實(shí)現(xiàn)金蜀,如果重現(xiàn)后的onInterceptTouchEvent放回為true,則intercepted = true狈醉,則不會(huì)進(jìn)入到真正的事件分發(fā)中廉油,也就是事件不能傳遞給子View。
分析onInterceptTouchEvent為true的情況苗傅。
接下來(lái)判斷這里:
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;
}
}
因?yàn)槲覀冮_(kāi)始的初始化狀態(tài)已經(jīng)把mFirstTouchTarget置空了抒线。所以這里進(jìn)入dispatchTransformedTouchEvent(ev,canceled,null,TouchTarget.ALL_POINTER_IDS);。點(diǎn)擊進(jìn)去這個(gè)方法渣慕。
// Perform any necessary transformations and dispatch.
// 第一次次 接下來(lái) 被攔截
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;
找到最后這部分代碼嘶炭。這里是事件傳遞的地方,因?yàn)閏hild的值為null逊桦,所以進(jìn)入到
handled = super.dispatchTouchEvent(transformedEvent);
點(diǎn)開(kāi)dispatchTouchEvent方法眨猎,你會(huì)發(fā)現(xiàn)這里跳到之前我們分析View的dispatchTouchEvent()方法,所以結(jié)合最上面的分析如果沒(méi)做其它的onTouch操作,則會(huì)順利的進(jìn)入到onTouchEvent(event)方法强经。到這里是否明白我們實(shí)現(xiàn)了攔截方法后事件不會(huì)傳遞到子View而是直接跳轉(zhuǎn)到了onTouchEvent(event)讓后結(jié)束睡陪。最后返回到MainActivity中,當(dāng)onTouchEvent()返回值會(huì)決定MainActivity會(huì)不會(huì)調(diào)用MainActivity自己的onTouchEvent(event)方法。
分析onInterceptTouchEvent為false的情況兰迫。
當(dāng)為false則會(huì)進(jìn)入到ViewGroup.dispatchTouchEvent方法中的判斷中:
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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);
//判斷是否有子View
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.
//<1>child重新排序
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//<2>事件分發(fā) 遍歷子控件
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
//preorderedList.get(childIndex)等價(jià)于
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 條件:clickable invisiable 點(diǎn)擊事件 不在view范圍中
* 還有正在動(dòng)畫(huà)中
*/
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
/**
* 絕對(duì)接收到事件
*/
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);
/**
* 真正做事件分發(fā)
* child 不為空
*/
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;
}
}
}
<1>先會(huì)判斷是否有子View遍歷子View信殊,讓后將這些View重新排序,為什么要進(jìn)行重新排序?是因?yàn)槎鄠€(gè)子View之間會(huì)存在重疊的現(xiàn)象汁果,點(diǎn)在重疊位置的時(shí)候事件是可以穿透的涡拘,誰(shuí)先接收到事件?誰(shuí)該執(zhí)行据德?在這之前的順序并不知道鳄乏。所以就需要先將子View重排序,按照重排序之后的順序執(zhí)行
<2>遍歷子View棘利,先判斷子View能否接收橱野,clickable、invisible赡译、點(diǎn)擊事件仲吏、不在view范圍中這幾種情況是不能接收那就直接放回。讓后執(zhí)行能接收到事件的View
newTouchTarget = getTouchTarget(child);
這里是找到直接接收事件的子View蝌焚,因?yàn)榈谝淮吸c(diǎn)擊newTouchTarget=null,所以不執(zhí)行下面if判斷。但如果是手指移動(dòng)的時(shí)候 就可以找到接收事件的子View誓斥,就不用繼續(xù)遍歷只洒。
讓后在dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)做事件分發(fā),這時(shí)候子View child不為空劳坑。繼續(xù)分析dispatchTransformedTouchEvent中的child不為空的方法毕谴。
// Perform any necessary transformations and dispatch.
// 第一次次 接下來(lái) 被攔截
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;
為什么這里需要 final float offsetX = mScrollX - child.mLeft;final float offsetY = mScrollY - child.mTop;因?yàn)閛ffsetX是子View相對(duì)屏幕邊的X方向的距離。怎么得到距芬?mScrollX是ViewGroup距離子控件的距離涝开,ViewGroup的邊可能在屏幕外面也可能在屏幕里面,child.mLeft是ViewGroup距離屏幕邊的距離框仔,當(dāng)ViewGroup超出屏幕child.mLeft的值是正的相減舀武,當(dāng)ViewGroup沒(méi)有超出屏幕child.mLeft的值是負(fù)的相加,offsetY同理离斩。
讓后執(zhí)行transformedEvent.transform银舱,這里是得到真正的相對(duì)屏幕距離
最后執(zhí)行子View的dispatchTouchEvent(transformedEvent)。到這里又和上面分析的情況一樣了跛梗。最后如果子View的onTouchEvent()有返回true寻馏,子View則會(huì)被添加到newTouchTarget鏈表中,讓后結(jié)束遍歷核偿;如果子View的onTouchEvent()的返回值都為false則newTouchTarget就沒(méi)有子View添加诚欠,newTouchTarget=null。
ViewGroup的dispatchTouchEvent后執(zhí)行到這里:
// 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;
}
}
mFirstTouchTarget到時(shí)候就不等于空了,到else里面轰绵,這里又進(jìn)行了一次dispatchTransformedTouchEvent()方法粉寞,target.child 不為空則handled=true最后也返回值也是true,如果target.child為空則根據(jù)上面分析的dispatchTransformedTouchEvent()方法又會(huì)到super.dispatchTouchEvent(transformedEvent);讓后執(zhí)行自己的onTouchEvent()方法
最后的到一張圖藏澳。
這里分析的是down事件仁锯,當(dāng)滑動(dòng)的時(shí)候,不會(huì)再進(jìn)入到循環(huán)遍歷里面了翔悠,如果之前已經(jīng)拿到childe业崖,newTouchTarget不為空則直接將事件傳遞給了相應(yīng)的子View,不用在做遍歷判讀了蓄愁。這就谷歌工程師優(yōu)化的地方双炕。
結(jié)束語(yǔ):
總算是分析完了,分析時(shí)候大致思路就是這樣撮抓,可能其中有一些沒(méi)說(shuō)清楚的妇斤,希望大家提給我,我會(huì)努力改好的