ViewGroup的事件分發機制


上一次我在View的事件分發機制里完整的分析了View對於觸屏點擊事件的分發過程,接下來繼續探索之旅,緊接着分析ViewGroup的事件分發機制,ViewGroup其實就是一組View的集合,它也是繼承於View的,它本身也可以包含ViewViewGroup,方便起見我們還是延用上一次的布局,不過這一次我們給根布局也設置了點擊事件和觸摸事件:

public class MainActivity extends Activity implements OnClickListener,OnTouchListener{

private RelativeLayout re_Layout;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button) findViewById(R.id.btn);
re_Layout=(RelativeLayout) findViewById(R.id.re_layout);
btn.setOnClickListener(this);
btn.setOnTouchListener(this);
re_Layout.setOnClickListener(this);
re_Layout.setOnTouchListener(this);
}
@Override
public void onClick(View v) {
Log.d("TAG", "OnClick--"+v);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TAG", "onTouch--"+event.getAction()+"--"+v);
return false;
}

}

這里寫圖片描述

效果圖也依舊沒有變,現在我們先點擊一下Button,查看Log輸出:
這里寫圖片描述

可以很清楚的看到這里和上一節分析得情況一樣:當點擊事件發生時onTouch()方法是優先於onClick()方法執行的,並且如果onTouch()返回False既不消耗點擊事件那么如果控件設置了setOnClickListener最終是會執行到onClick()方法的,可是我很好奇ViewGroup的點擊事件和View的到底有什么區別,點擊事件事件的分發到底是從ViewGroup開始還是從View開始的呢,於是我點擊了Button以外的空白區域,捕捉到如下信息(注:我的根布局就是RelativeLayout):
這里寫圖片描述

說明根布局也就是Viewroup也是可以響應點擊事件的,但是我們點擊View的時候為什么沒有ViewGroup的Log輸出,這是不是說明android事件分發是先傳到View的,當View消耗的這個事件它的ViewGroup就無法接收這個事件了呢,為了徹底的談清楚原因,我們先重寫一個ViewGroup,然后重寫這個ViewGroup里面的onInterceptTouchEvent(MotionEvent ev)dispatchTouchEvent(MotionEvent event)還有onTouchEvent(MotionEvent event)這三個方法通過Log輸出信息來判斷:

public class MyLayout extends RelativeLayout{

public MyLayout(Context context,AttributeSet attrs) {
super(context,attrs);

}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("TAG", ev.getAction()+" action"+"MyLayout onInterceptTouchEvent");
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("TAG", event.getAction()+" action"+"MyLayout onTouchEvent");
return super.onTouchEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("TAG", ev.getAction()+" action"+"MyLayout dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}

同理我們還需要重寫一個Button:

public class MyButton extends Button{
public MyButton(Context context,AttributeSet attrs){
super(context,attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("TAG", event.getAction()+" action"+"MyButton onTouchEvent");
return super.onTouchEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("TAG", ev.getAction()+" action"+"MyButton dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
//這里注意View是沒有onInterceptTouchEvent方法的

效果圖是一樣的這里就不再貼了,為了驗證剛才的想法我們直接點擊一下界面上的Button,Log輸出如下:
這里寫圖片描述

發現了什么,我們點擊的是Button,然而這個事件最開始是傳到了我們的根布局MyLayout,並且還按照:
dispatchTouchEventonInterceptTouchEventdispatchTouchEvent的順序執行,緊接着執行ViewonTouch()onTouchEvent()方法,還有一點很奇怪的事只有最開始ACTION_DOWN的時候調用了ViewGroup的onInterceptTouchEvent方法,在后面的ACTION_UP事件派發過程中卻沒有調用,這里給出一個合理的猜想:一旦一個View開始處理這個觸摸事件,那么接下來的ACTION_MOVE和ACTION_UP事件都會交給它去處理,就好比你在公司里面做事,分到你做的事你已經做了一些,那么接下來的事你的完完整整的做好,那么如果做到一半不做了會怎么樣(即View不消耗ACTION_DOWN事件)?我們可以大膽的假設如果上級交給你做的事沒有做好,那么上級_在短期內肯定不敢交代事情給你做了(后續的ACTION_MOVE、ACTION_DOWN事件這個View都接收不到了),那么究竟如何我們還是從源碼看起。

我們已經知道當一個點擊操作發生時事件是先傳給ViewGroup處理的並且首先執行的是ViewGroupdispatchTouchEvent,那么我們就先來看看它的源碼:

 /**
* {@inheritDoc}
*/

@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 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.
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(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;
}

相當長,還是一點點來看,源碼這種東西看不懂肯定會覺得很枯燥,所以能弄懂的盡量弄懂,最開始只是一些對View是否可以獲得焦點的判斷、設置標志位以及初始化一些布爾值,並且在ACTION_DOWN事件產生的時候清楚以外的狀態並且准備開始新一輪的手勢操作,不重要:

     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;
}

這里首先設立了一個布爾值interception去判斷當前ViewGroup是否要攔截View的點擊事件,if條件語句中的內容是當產生ACTION_DOWN按下事件或者mFirstTouchTarget != null的時候去判斷是否要攔截當前事件,這里主要關注mFirstTouchTarget != null這個點,我們找一找哪個方法跟這個mFirstTouchTarget變量有關,還真給我找到了,看下面:

 private void clearTouchTargets() {
TouchTarget target = mFirstTouchTarget;
if (target != null) {
do {
TouchTarget next = target.next;
target.recycle();
target = next;
} while (target != null);
mFirstTouchTarget = null;
}
}
/**
* Cancels and clears all touch targets.
*/

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();
}
}
}

這兩段代碼結合起來,在加上在ACTION_DOWN初始時候是調用了cancelAndClearTouchTargets(MotionEvent event)這個方法的,所以我們可以推薦起初這個mFirstTouchTarget 的值是null的,那么mFirstTouchTarget是在哪里賦值的呢,我們在dispatchTouchEvent(MotionEvent ev)接着往下看:

 newTouchTarget = addTouchTarget(child, idBitsToAssign);

我們看到newTouchTarget是在這里賦值的,看一下addTouchTarget方法:

 /**
* Adds a touch target for specified child to the beginning of the list.
* Assumes the target child is not already present.
*/

private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
mFirstTouchTarget = target;
return target;
}

從該方法的內部結構可以看出,mFirstTouchTarget其實是一中單鏈表結構,如果找到了處理該點擊事件的子View那么mFirstTouchTarget就會被賦值並且會指向子元素。
這一下弄清楚了回到剛才的那段代碼:

  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;
}
 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

這個布爾值是判斷子元素是否調用了requestDisallowInterceptTouchEvent這個方法,如果調用了這個布爾值就為True,這里看一眼這個方法的代碼:

 /**
* {@inheritDoc}
*/

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);
}
}

你可以在子View中調用這個方法來讓ViewGroup不攔截除了ACTION_DOWN以外的點擊事件,這里為什么說是ACTION_DOWN以外呢,因為ViewGroup在分發事件的時候最開始是會重置FLAG_DISALLOW_INTERCEPT這個標志位的,所以無論你有沒有在子View中設置requestDisallowInterceptTouchEvent方法都不會影響到ViewGroup去攔截ACTION_DOWN事件的,接着往下看:

  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;
}

如果子View沒有設置requestDisallowInterceptTouchEvent方法那么就調用ViewGrouponInterceptTouchEvent(ev)方法,我們找到這個方法:

  /**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}

唔,注釋相當長,但是有用的就一個返回值,這里返回False,說明ViewGrup不攔截點擊事件,事件可以繼續往下傳遞,這個方法的最后,如果當前界面除了一個ViewGroup沒有任何子View,那么此時ViewGroup也會攔截點擊事件,就好比一個公司人手不夠,公司領導需要親力親為一樣。
接着:

// 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);

}

如果確定攔截或者已經有子View着手處理這個點擊事件,那么就開始正常的事件分發流程。

 final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;

這里是通過標志位和ACTION_CANCLE來檢查是否cancle,再下去:

 final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;

首先可以看見獲取一個boolean變量標記split來標記,默認是true,作用是是否把事件分發給多個子View,這個同樣在ViewGroup中提供了public的方法設置,如下:

public void setMotionEventSplittingEnabled(boolean split) {
// TODO Applications really shouldn't change this setting mid-touch event,
// but perhaps this should handle that case and send ACTION_CANCELs to any child views
// with gestures in progress when this is changed.
if (split) {
mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
} else {
mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
}
}

這一段摘自:Android觸摸屏事件派發機制詳解與源碼分析二(ViewGroup篇)  

    if (!canceled && !intercepted) {

如果沒有取消當前動作並且ViewGroup未攔截事件那么事件就傳遞到接收了該點擊事件的View,接下來是一大段代碼預警:

 // 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.
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(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;
}

嗯,這段代碼的邏輯比較清晰,大體上就是遍歷ViewGroup的所有子元素,然后判斷子元素是否能夠接收到點擊事件,接收的依據有兩種:第一種是判斷子元素是否在播放動畫,第二種是判斷點擊事件的坐標是否落在子元素的區域內,從這里可以看出來:

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;
}

如果子元素滿足了這兩個條件,點擊事件就會交給它處理,接下來這段代碼里面有一個很重要的方法:

       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;
}

這里if判斷里面這個dispatchTransformedTouchEvent是將Touch事件傳遞給特定的子View,它實際上在內部是調用了子元素的disPatchTouchEvent方法,找一下它的源碼:

    /**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/

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 (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}

如果傳遞的child為null就調用父類的dispatchTouchEvent否則就調用子類的dispatchTouchEvent,而上面的代碼中child不為null,所以執行子元素的dispatchTouchEvent,如果子元素的dispatchTouchEvent返回的是True,那么含有dispatchTransformedTouchEvent這個方法內部的for循環就不會繼續下去,直接跳到這里:

 mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;

這個地方前面說過是給mFirstTouchTarget賦值的地方,如果情況改變,前面那個dispatchTransformedTouchEvent方法中child返回的是False,那么如果當前ViewGroup會把點擊事件傳遞給下一個子元素進行處理,執行for循環查找下一個子元素,此時mFirstTouchTarget依然未被賦值為null,那么這時候繼續查看接下來的代碼:

     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並且我們的mFirstTouchTarget!=null那么就把最開始的TouchTarget賦值給newTouchTarget,最后:

 // 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);

執行到這里的話有兩種情況,一種是ViewGroup里面沒有找到子View,另一種就是找到了處理這次點擊事件的子View但是這個子View的disPatchTouchEvent返回了False,我們通過前面的分析知道disPatchTouchEvent中是先執行onTouch()方法的,而一般onTouch()方法返回的是False,此時disPatchTouchEvent方法的返回值由onTouchEvent方法決定,出現這種情況說明onTouchEvent返回了False,在以上兩種情況下,ViewGroup會自己處理這個點擊事件,注意這里這個方法里的child傳入的是null,我們前面就知道了傳入null會執行handled = super.dispatchTouchEvent(event);也就是說此時交由ViewGroup處理這個事件。而ViewGroup也是View的子類,它里面是沒有重寫ViewonTouchEvent方法的,所以它自身處理點擊事件的流程和我們在View的事件分發機制解析里面分析得是一樣的,至此ViewGroup的分發事件分析完畢。

這次我們只分析了點擊Button時的Log輸出,下面給出點擊空白處的Log輸出,可以自己檢驗一下分析成果:
這里寫圖片描述

一些結論:

  • ViewGroup默認不攔截任何事件,Android源碼中ViewGrouponInterceptTouchEvent方法默認返回false
  • ViewonTouchEvent默認都會消耗事件(返回true),除非是不可點擊的(clickablelongClicjable同時為false),ViewlongClickable屬性默認是false
  • Viewenable屬性不會影響onTouchEvent的返回值,哪怕該Viewdisable的,只要它的clickablelongClickable其中一個為true,那么它的onTouchEvent就返回true
  • 事件傳遞過程是由外向內的,即事件總是先傳給父元素,然后再由父元素分發給子VIew,子View可以通過requestDisallowInterceptTouchEvent來干預父元素的分發過程,但是影響不到ACTION_DOWN事件

參考:
Android觸摸屏事件派發機制詳解與源碼分析二(ViewGroup篇)
Android事件分發機制完全解析,帶你從源碼的角度徹底理解(下)

寫東西很辛苦,如果覺得寫的還看得過去的話請點個贊吧。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com