首先惧互,我們分析不做任何處理事件是如何分發(fā)的
android 事件分發(fā)是我們開發(fā)安卓必須知道的知識點(diǎn)鸦概,無論是開發(fā)中還是面試梨撞,都經(jīng)常遇到事件分發(fā)類的問題何鸡,今天我們就從源碼層進(jìn)行深度剖析。
首先我們給定一個布局
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
這個布局我們不做任何處理筛璧,那么當(dāng)我點(diǎn)擊 Hello World 這個文本控件后逸绎,會有一個點(diǎn)擊事件,下面就讓我們來追蹤這個點(diǎn)擊事件
首先我們需要知道誰最先接收到這個點(diǎn)擊事件夭谤,我來告訴你棺牧,就是在源碼 Activity 中的dispatchTouchEvent方法,為什么是這個方法呢朗儒,就是這么設(shè)計的颊乘,手點(diǎn)擊屏幕,觸發(fā)屏幕傳感器醉锄,再通過底層硬件代碼調(diào)用乏悄,然后就到這個方法里了。
/**
* 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.
(調(diào)用以處理觸摸屏事件恳不。您可以覆蓋此選項(xiàng)檩小,以便在將所有觸摸屏事件發(fā)送到窗口之前截獲它們。對于應(yīng)該正常處理的觸摸屏事件烟勋,一定要調(diào)用此實(shí)現(xiàn)规求。)
*
* @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);
}
記住標(biāo)題,我們假設(shè)的是不做任何處理卵惦,然后看事件的分發(fā)
我們在方法中可以看到
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
因?yàn)椴蛔鋈魏翁幚碜柚祝赃@個地方不能return ture,
也就是說getWindow().superDispatchTouchEvent(ev)要為false,
我們進(jìn)入getWindow().superDispatchTouchEvent(ev)
然后在Window文件中發(fā)現(xiàn)了抽象方法
public abstract boolean superDispatchTouchEvent(MotionEvent event);
然后我們進(jìn)入Window抽象類的實(shí)現(xiàn)類PhoneWindow,找到方法
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
進(jìn)入mDecor.superDispatchTouchEvent(event)
然后來到 DecorView
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
這個時候來到了ViewGroup文件的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.
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;
}
// 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 (!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;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
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;
}
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);
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.
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;
}
以上是dispatchTouchEvent方法的全部內(nèi)容,下面我拆分講解
首先我們假設(shè)文章開頭給的布局里面沮尿,RelativeLayout 外面沒有別的布局了冕茅,因?yàn)镽elativeLayout 里面還有一個TextView,所以這個點(diǎn)擊事件必然還要向下傳遞,所以我們直接來到遍歷子View的地方
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex( childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
在這里我們找到了for循環(huán)蛹找,在循環(huán)里,我們需要注意child 的處理
在下面我們發(fā)現(xiàn)代碼
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))
很顯然哨坪,這里dispatchTransformedTouchEvent也需要返回false,我們進(jìn)入該方法,找到代碼塊
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);
}
很顯然庸疾,我們這里還有TextView,所以這個View為TextView,不為空当编,點(diǎn)擊事件又給了子View的dispatchTouchEvent届慈,就是調(diào)用了
handled = child.dispatchTouchEvent(event);
由于我們未做任何處理,所以 child.dispatchTouchEvent(event) 也要返回false,我們進(jìn)入該方法,發(fā)現(xiàn)代碼塊
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
if (!result && onTouchEvent(event)) {
result = true;
}
這里正好可以補(bǔ)充一個知識點(diǎn)金顿,我們發(fā)現(xiàn)如果 li.mOnTouchListener != null臊泌,那么就會調(diào)用 && li.mOnTouchListener.onTouch(this, event),然后返回了true,默認(rèn)消費(fèi)了這次的事件揍拆,這就是為什么如果我們設(shè)置了OnTouchListener后就不會再調(diào)用onTouch方法
當(dāng)然了渠概,這個地方li.mOnTouchListener肯定為空,所以事件又給了onTouchEvent方法嫂拴,當(dāng)然播揪,這個地方也還是返回false,然后我再重新回到View的dispatchTouchEvent,還是返回false,再繼續(xù)返回至ViewGroup的dispatchTouchEvent方法里筒狠,就是循環(huán)遍歷子View的地方猪狈,進(jìn)過這一輪遍歷,沒有一個子View消費(fèi)點(diǎn)擊事件的辩恼,那么代碼繼續(xù)往下走雇庙,發(fā)現(xiàn)了代碼塊
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
以為沒有子View消費(fèi),所以mFirstTouchTarget 為空灶伊,因?yàn)閂iewGroup也沒有消費(fèi)點(diǎn)擊事件疆前,所以dispatchTransformedTouchEvent還是返回false,我們注意入?yún)ⅲl(fā)現(xiàn)傳View的地方傳了一個null,我們進(jìn)入該方法谁帕,還是同樣的代碼
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);
}
只不過這次不在是child.dispatchTouchEvent(event);峡继,而是super.dispatchTouchEvent(event);
同理進(jìn)去我們發(fā)現(xiàn)它把事件又給了自己的onTouchEvent,然后繼續(xù)返回false
此時代碼再繼續(xù)往下走匈挖,方法結(jié)束碾牌,返回false,這個時候又進(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)為false,直接返回了自己的onTouchEvent儡循,自此一個點(diǎn)擊事件的旅程結(jié)束
這個ViewGroup是一個遞歸調(diào)用舶吗,其實(shí)這個地方有好多個ViewGroup
網(wǎng)上也有很多博客是這么說的
注意,這個是不嚴(yán)謹(jǐn)?shù)脑裣ィ蛘哒f是錯誤的
好誓琼,以上是不做處理,那么下面我寫幾種情況
1肴捉、ViewGroup 的 onTouchEvent進(jìn)行自定義處理腹侣,返回true
2、ViewGroup 的 onInterceptTouchEvent進(jìn)行自定義處理齿穗,返回true
3傲隶、View 的 onTouchEvent進(jìn)行自定義處理,返回true
版權(quán)聲明:個人原創(chuàng)窃页,若轉(zhuǎn)載跺株,請注明出處