觸控事件分析
已開通新的部落格,後續文字都會發到新部落格
概述
初始化
每一個事件流,都是以ACTION_DOWN作為開始,以ACTION_UP或ACTION_CANCEL作為結束
在處理開始前,需要做一個安全處理,即是否有不可見的window覆蓋其上,防止有惡意軟體劫持使用者輸入事件
如果是DOWN事件,那麼表示要開始一個新的事件流,這時就需要清理原來的狀態,重新開始
攔截
接來下檢查父View是否會攔截事件,如果父View希望攔截,也就是在onInterceptTouchEvent()
中返回true
,那麼後續將不再尋找有意願接收事件的子View,而是將事件直接發給父View的onTouchEvent來處理
比如說,長按列表中某個項,子View會處理長按事件,長按然後開始滑動,父View會接管滑動事件,列表就開始滑動,同時子View就恢復狀態。這個邏輯就是通過事件攔截實現的。
請求不攔截
當然,子View也可以要求父View不要攔截這個事件
比如說,長按列表中某個項,然後上下拖動,改變子View的順序,這個邏輯就需要子View告知父View不要攔截處理,交給我就可以了
子View是通過requestDisallowInterceptTouchEvent()
方法來請求父View不要攔截事件
然後檢視這個事件是否是取消事件,取消事件的話也不會去找VIew分發了,因為這是一個結束事件,所以要通知之前分發過的view,事件已經被其他View接管
查詢想要接管的View
只有事件即沒有被攔截,也不是取消事件,才會找新的view接管
遍歷自己的view樹,然後找願意接管事件的view,(從最接近使用者的那個view開始),找到之後,標記這個view為target,接下來的事件就不在找了,直接轉發給這個view,這是正常的事件流
被攔截或者是取消事件
那麼對於攔截或者取消的情況呢:
如果在這之前還沒有找過view接管,那麼直接傳給當前view處理
如果曾找過view接管,
對於攔截事件,分發給子view事件被取消了,方便子view做後續處理
對於取消事件,要分發給子view,告訴事件取消
簡化模型
以上事件的分發過程,可以使用下邊的簡化模型來理解
public boolean disaptchTouchEvent(MotionEvent ev){
boolean handled = false;
if (onInterceptTouchEvent(ev)) {
handled = onTouchEvent(ev);
}else{
handled = child.dispatchTouchEvent(ev);
}
return handled;
}
流程分析
@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) { // 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) {// 事件流開始或者已經找到要分發的view
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) { // 是否允許父view攔截
intercepted = onInterceptTouchEvent(ev); // 父View是否攔截
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;// newTarget標識是否和原來的target有變化,來判斷是否已經分發過了
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) { // 不是取消事件,也不是攔截事件(如果是二者,那麼不找新的target,直接進行分發,cancel分發給子view,攔截分發給自己)
// 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) {//viewgroup是不是空的
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();// 獲取直接子View,而不是子孫View
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) {// 如果有輔助View,那麼我們就要確保先找到這個輔助View,然後從頭開始正常分發
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
if (!canViewReceivePointerEvents(child) //如果view不可以接收觸控事件 且 事件座標範圍不在view內,那麼跳過繼續尋找
|| !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;// 找到了有意願處理觸控事件的view,不再繼續往下找
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {// 找到可以分發的,跳出迴圈
// Child wants to receive touch within its bounds. // 找到了,(注意,只有ACTION_DOWN才能進行到這一步,MOVE等事件在上一步就已經找好了
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);// 新加入的touchTarget加入列表頭
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;// 表明事件之前已經分發過了。所以有target記錄
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;
}