我們都知道淫奔,用戶與app進(jìn)行交互都是通過activity來進(jìn)行的,而我們平時(shí)在activity中設(shè)置的view是怎么接收到用戶交互的事件呢怨绣,activity與view又有怎么樣的層級(jí)關(guān)系呢?我們來看一個(gè)很簡(jiǎn)單的頁(yè)面:
圖一
圖二
圖三
從三張圖我們可知,我們?cè)赼ctivity中通過setContentView設(shè)置的view就是圖一中的ContentViews部分钻注,它的根布局是FrameLayout,也是圖二中的紅色區(qū)域配猫。圖三中的紅色區(qū)域就是圖一中的TitleView幅恋。知道了activity與view的層級(jí)關(guān)系后,那么事件是怎么一步步傳到view中的呢泵肄?
首先來看Activity中的實(shí)現(xiàn):
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
* Called to process touch screen events. You can override this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event.
* * @return boolean Return true if this event was consumed.
*/ public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}</pre>
大概意思就是捆交,如果Window的superDispatchTouchEvent返回true,表示Activity將該事件傳遞給Window來處理腐巢,如果返回false品追,則Activity自行處理該事件,Activity的onTouchEvent將會(huì)被調(diào)用冯丙,
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
* Called when a touch screen event was not handled by any of the views * under it. This is most useful to process touch events that happen * outside of your window bounds, where there is no view to receive it. * * @param event The touch screen event being processed.
* * @return Return true if you have consumed the event, false if you haven't.
* The default implementation always returns false. */ public boolean onTouchEvent(MotionEvent event) {
if (mWindow.shouldCloseOnTouch(this, event)) {
finish();
return true;
}
return false;
}</pre>
下面再來看看Window的superDispatchTouchEvent返回true的情況肉瓦,由于Window的實(shí)現(xiàn)類為PhoneWindow,
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">@Override public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}</pre>
有此可知調(diào)用了mDecor胃惜,mDecor就是DecorView泞莉,是根View,繼承至FrameLayout
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}</pre>
關(guān)于點(diǎn)擊事件如何在View中進(jìn)行分發(fā)船殉,點(diǎn)擊事件到達(dá)頂級(jí)view(一般是一個(gè)ViewGroup)鲫趁,會(huì)調(diào)用ViewGroup的dispatchTouchEvent方法,當(dāng)ACTION_DOWN事件發(fā)生后捺弦,如果ViewGroup選擇攔截該事件饮寞,那么接下來的ACTION_MOVE和ACTION_UP等這一事件序列的所有事件都不能被傳遞給ViewGroup的子View孝扛,都交給了ViewGroup進(jìn)行處理,所以說幽崩,ViewGroup不能攔截ACTION_DOWN事件苦始,否則子view將接收不到任何事件。ViewGroup不攔截ACTION_DOWN事件慌申,則交給子View進(jìn)行出來陌选,接著會(huì)調(diào)用子view的dispatchTouchEvent事件,如果子view的dispatchTouchEvent返回true表示消費(fèi)該事件蹄溉,否則表示不消費(fèi)該事件(會(huì)將該事件又返回給父ViewGroup進(jìn)行處理)咨油。
[圖片上傳失敗...(image-e9c0ad-1624893293481)]
如果事件交由ViewGroup進(jìn)行處理,執(zhí)行ViewGroup的超類View的dispatchTouchEvent方法柒爵,這時(shí)如果ViewGroup的mOnTouchListener被設(shè)置了役电,就會(huì)執(zhí)行OnTouchListener的onTouch方法,如果onTouch方法返回false棉胀,則接著會(huì)執(zhí)行onTouchEvent方法
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them. return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
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)) {
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:
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(0, x, y);
break;
}
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:
if (clickable) {
setPressed(false);
}
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
break;
case MotionEvent.ACTION_MOVE:
if (clickable) {
drawableHotspotChanged(x, y);
}
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
// Remove any future long press/tap checks removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
break;
}
return true;
}
return false;
}</pre>
onTouchEvent會(huì)判斷該ViewGroup是否是可點(diǎn)擊的法瑟,也就是是否設(shè)置了mOnClickListener,如果設(shè)置了表示消費(fèi)該事件唁奢,onClick將會(huì)被調(diào)用霎挟。否則也就表示不消費(fèi)該事件,該事件還是會(huì)被拋給當(dāng)前的父View進(jìn)行處理麻掸。當(dāng)ViewGroup不攔截此事件酥夭,會(huì)交給子View進(jìn)行處理,然后再一次執(zhí)行dispatchTouchEvent方法脊奋。到此為止熬北,事件已經(jīng)從頂級(jí)View傳遞給了下一層的View,接下來的傳遞過程和頂級(jí)View是一致的诚隙,如此循環(huán)蒜埋,完成整個(gè)事件的分發(fā)。
所以我們接著看ViewGroup的dispatchTouchEvent最楷,
[圖片上傳失敗...(image-72149b-1624893293479)]
當(dāng)發(fā)生ACTION_DOWN事件時(shí),cancelAndClearTouchTargets會(huì)將mFirstTouchTarget重置為null待错,resetTouchState會(huì)將mGroupFlags置為0籽孙。
從上面代碼我們可以看出,ViewGroup在如下兩種情況下會(huì)判斷是否要攔截當(dāng)前事件:事件類型為ACTION_DOWN或者mFirstTouchTarget != null火俄,ACTION_DOWM 好理解犯建,那么mFirstTouchTarget是什么呢,由后面的代碼可知瓜客,mFirstTouchTarget在ViewGroup將事件傳遞給子view時(shí)适瓦,mFirstTouchTarget會(huì)被賦值并被指向子元素竿开。
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">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;
}</pre>
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
* Adds a touch target for specified child to the beginning of the list. * Assumes the target child is not already present. */ private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}</pre>
也就是當(dāng)ViewGroup不攔截事件并將事件交由子元素處理時(shí),mFirstTouchTarget != null玻熙。反過來否彩,一旦ViewGroup需要攔截此事件,mFirstTouchTarget != null就不成立了嗦随。那么當(dāng)ACTION_UP和ACTION_MOVE事件到來時(shí)列荔,actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null就不成立了,將導(dǎo)致ViewGroup的onInterceptTouchEvent不會(huì)被調(diào)用枚尼,intercepted為true贴浙,并且同一事件序列的其他事件也默認(rèn)交給ViewGroup處理。
當(dāng)然署恍,這里有一種特殊情況崎溃,那就是FLAG_DISALLOW_INTERCEPT標(biāo)記位,這個(gè)標(biāo)記位是通過requestDisallowInterceptTouchEvent方法設(shè)置的盯质,
<pre style="margin: 0.667rem 0px; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; font-family: Menlo; font-size: 9pt;">/**
* Called when a child does not want this parent and its ancestors to * intercept touch events with * {@link ViewGroup#onInterceptTouchEvent(MotionEvent)}.
* * <p>This parent should pass this call onto its parents. This parent must obey
* this request for the duration of the touch (that is, only clear the flag * after this parent has received an up or a cancel.</p> ** @param disallowIntercept True if the child does not want the parent to
* intercept touch events. */ public void requestDisallowInterceptTouchEvent(boolean disallowIntercept);</pre>
一般用于子View中袁串。FLAG_DISALLOW_INTERCEPT一旦設(shè)置后,ViewGroup將無(wú)法攔截除了ACTION_DOWN以外的點(diǎn)擊事件唤殴。為什么說出了ACTION_DOWN以外其他點(diǎn)擊事件般婆,是因?yàn)榘l(fā)生ACTION_DOWN事件時(shí),會(huì)重置mGroupFlags標(biāo)記位朵逝,還會(huì)置mFirstTouchTarget為null蔚袍,將導(dǎo)致子View設(shè)置的標(biāo)記位失效。因此當(dāng)發(fā)生ACTION_DOWN事件時(shí)配名,ViewGroup總是詢問自己是否要攔截事件啤咽,從上面代碼就可以看出。當(dāng)ViewGroup決定攔截事件時(shí)渠脉,后續(xù)這一事件序列里的所有事件都默認(rèn)交給ViewGroup自己處理并且不再調(diào)用onInterceptTouchEvent方法宇整。設(shè)置mGroupFlags為FLAG_DISALLOW_INTERCEPT的作用就是讓ViewGroup不再攔截事件,前提時(shí)ACTION_DOWN事件沒有被ViewGroup攔截芋膘。