View事件分發(fā)(傳遞)機(jī)制
前言:View事件分發(fā)機(jī)制是Android中比較重要和復(fù)雜的部分按价,只有理解了事件分發(fā)除呵,才能更好的自定義控件和解決滑動(dòng)沖突,本篇文章基于API25(7.1)业簿。
相關(guān)方法
- public boolean disptachTouchEvent(MotionEvent ev)
事件分發(fā)方法隔箍,觸控事件從該方法開(kāi)始傳遞,返回true表示分發(fā)完成坎背,返回false則失敗
- public boolean onInterceptTouchEvent(MotionEvent ev)
事件攔截方法替劈,只有ViewGroup中才存在,在dispatchTouchEvent中判斷是否攔截事件由自己處理得滤,或者交給子View(ViewGroup)分發(fā)陨献,返回true表示攔截事件,默認(rèn)返回false
- public boolean onTouchEvent(MotionEvent ev)
事件處理方法懂更,處理事件眨业,返回true表示消耗事件,返回false表示不消耗事件
dispatchTouchEvent | OnInterceptTouchEvent | onTouchEvent | |
---|---|---|---|
Activity | √ | × | √ |
ViewGroup | √ | √ | √ |
View | √ | × | √ |
源碼分析
Activity
/**
* 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);
}
/**
* Retrieve the current {@link android.view.Window} for the activity.
* This can be used to directly access parts of the Window API that
* are not available through Activity/Screen.
*
* @return Window The current window, or null if the activity is not
* visual.
*/
public Window getWindow() {
return mWindow;
}
事件首先從Activity的disptachTouchEvent的方法開(kāi)始調(diào)用沮协,調(diào)用了Window的superDispatchTouchEvent方法龄捡,至于事件MotionEvent的來(lái)源不在本章討論的范圍內(nèi)
/**
* 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;
}
Activity默認(rèn)不會(huì)消耗事件
Window
可以看到這是個(gè)抽象方法,Window是一個(gè)抽象類慷暂,Window的唯一實(shí)現(xiàn)是PhoneWindow
/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window {
...
/**
* Used by custom windows, such as Dialog, to pass the touch screen event
* further down the view hierarchy. Application developers should
* not need to implement or call this.
*
*/
public abstract boolean superDispatchTouchEvent(MotionEvent event);
...
}
PhoneWindow
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
PhoneWindow的該方法代碼就一行聘殖,調(diào)用了DecorView的superDisptachTouchEvent方法
DecorView
/** @hide */
public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
...
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
...
}
DecorView調(diào)用了父類FrameLayout的disptachTouchEvent,F(xiàn)rameLayout繼承于ViewGroup行瑞,且沒(méi)有重寫該方法奸腺,所以終于到了ViewGroup的dispatchTouchEvent方法,下面開(kāi)始重點(diǎn)
ViewGroup
ViewGroup的dispatchTouchEvent方法比較長(zhǎng)血久,先分開(kāi)看
dispatchTouchEvent#1
// 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;
}
首先在ACTION_DOWN中清除所有的觸摸狀態(tài)和目標(biāo), 然后檢查是否需要攔截事件突照,當(dāng)為ACTION_DOWN事件,首選檢查標(biāo)志位FLAG_DISALLOW_INTERCEPT是否已設(shè)置氧吐,即是否不攔截事件讹蘑,通過(guò)requestDisallowInterceptTouchEvent方法可以設(shè)置該標(biāo)志位末盔,默認(rèn)沒(méi)有設(shè)置,disallowIntercept是false衔肢,如果已設(shè)置該標(biāo)志位庄岖,則不截?cái)嘧覸iew(ViewGroup)事件,否則會(huì)調(diào)用自身的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);
}
}
/**
* @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) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
可以看到ViewGroup默認(rèn)情況是不會(huì)攔截事件隅忿,所以接下來(lái)遍歷子View,并調(diào)用disptachTransformedTouchEvent
dispatchTouchEvent#2
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 (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;
}
...
}
}
如果有符合條件的child(觸摸點(diǎn)和變換后的點(diǎn)在該View內(nèi))對(duì)應(yīng)于dispatchTransformedTouchEvent返回true的邦尊,則newTouchTraget = addTouchTarget(child, idBitsToAssign)
會(huì)走到
/**
* 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;
}
可以看到如果mFirstTouchTarget賦值了背桐,則后續(xù)事件序列繼續(xù)走進(jìn)第一步事件攔截判斷語(yǔ)句內(nèi),否則后續(xù)的事件序列都由該ViewGroup攔截
/**
* 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 the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
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);
}
// Perform any necessary transformations and dispatch.
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;
}
可以看到如果child為null則會(huì)調(diào)用ViewGroup父類的dispatchTouchEvent,ViewGroup的父類是View則會(huì)走到View的dispatchTouchEvent中蝉揍;否則會(huì)調(diào)用child的dispatchTouchEvent链峭,即事件繼續(xù)傳遞下去
disptachTouchEvent#3
// 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為null,即ViewGroup攔截事件或者ViewGroup沒(méi)有child消耗該事件又沾,則調(diào)用super#disptachTouchEvent否則調(diào)用child的dispatchTouchEvent,如果child不消耗ACTION_DOWN除外的事件弊仪,則該事件消失,不會(huì)回傳給父ViewGroup杖刷,最終會(huì)傳給Activity的onTouchEvent励饵,并且后續(xù)的事情此child也能收到。如果ViewGroup在ACTION_MOVE中攔截事件滑燃,則會(huì)走到dispatch(ev,true,target.child,target.pointIdBits)中役听,在該方法中child會(huì)收到一個(gè)ACTION_CANCEL事件,VieGroup不處理該事件表窘,且predecessor == null
典予,mFirstTouchTarget = next
最終,mFirstTouchTarget置為null乐严,從下個(gè)事件開(kāi)始都交由ViewGroup處理瘤袖。
View
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
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);
}
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;
}
//noinspection SimplifiableIfStatement
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;
}
}
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;
}
首先會(huì)檢查是否該View會(huì)設(shè)置OnTouchListener、是否enable昂验、onTouchListener.onTouch(this,event)是否返回true孽椰,如果條件都滿足則標(biāo)識(shí)該View消耗了事件,傳遞完成凛篙,否則會(huì)繼續(xù)調(diào)用onTouchEvent
/**
* Implement this method to handle touch screen motion events.
* <p>
* If this method is used to detect click actions, it is recommended that
* the actions be performed by implementing and calling
* {@link #performClick()}. This will ensure consistent system behavior,
* including:
* <ul>
* <li>obeying click sound preferences
* <li>dispatching OnClickListener calls
* <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
* accessibility features are enabled
* </ul>
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
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)) {
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;
}
如果控件不是enable的,但是是可以點(diǎn)擊的clickable栏渺、longClickable或者contextClickable的也會(huì)消耗該事件呛梆;如果控件是enable的,則會(huì)根據(jù)事件的時(shí)間長(zhǎng)短來(lái)執(zhí)行checkForLongClick或者perfomrClick方法,可點(diǎn)擊的View的onTouchEvent默認(rèn)返回true磕诊,如Button填物,不可點(diǎn)擊的則返回false纹腌,如TextView和ImageView
private void checkForLongClick(int delayOffset, float x, float y) {
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.setAnchor(x, y);
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress,
ViewConfiguration.getLongPressTimeout() - delayOffset);
}
}
private final class CheckForLongPress implements Runnable {
private int mOriginalWindowAttachCount;
private float mX;
private float mY;
@Override
public void run() {
if (isPressed() && (mParent != null)
&& mOriginalWindowAttachCount == mWindowAttachCount) {
if (performLongClick(mX, mY)) {
mHasPerformedLongPress = true;
}
}
}
public void setAnchor(float x, float y) {
mX = x;
mY = y;
}
public void rememberWindowAttachCount() {
mOriginalWindowAttachCount = mWindowAttachCount;
}
}
/**
* Calls this view's OnLongClickListener, if it is defined. Invokes the
* context menu if the OnLongClickListener did not consume the event,
* anchoring it to an (x,y) coordinate.
*
* @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
* to disable anchoring
* @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
* to disable anchoring
* @return {@code true} if one of the above receivers consumed the event,
* {@code false} otherwise
*/
public boolean performLongClick(float x, float y) {
mLongClickX = x;
mLongClickY = y;
final boolean handled = performLongClick();
mLongClickX = Float.NaN;
mLongClickY = Float.NaN;
return handled;
}
/**
* Calls this view's OnLongClickListener, if it is defined. Invokes the
* context menu if the OnLongClickListener did not consume the event.
*
* @return {@code true} if one of the above receivers consumed the event,
* {@code false} otherwise
*/
public boolean performLongClick() {
return performLongClickInternal(mLongClickX, mLongClickY);
}
/**
* Calls this view's OnLongClickListener, if it is defined. Invokes the
* context menu if the OnLongClickListener did not consume the event,
* optionally anchoring it to an (x,y) coordinate.
*
* @param x x coordinate of the anchoring touch event, or {@link Float#NaN}
* to disable anchoring
* @param y y coordinate of the anchoring touch event, or {@link Float#NaN}
* to disable anchoring
* @return {@code true} if one of the above receivers consumed the event,
* {@code false} otherwise
*/
private boolean performLongClickInternal(float x, float y) {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
boolean handled = false;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnLongClickListener != null) {
handled = li.mOnLongClickListener.onLongClick(View.this);
}
if (!handled) {
final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y);
handled = isAnchored ? showContextMenu(x, y) : showContextMenu();
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
/**
* Call this view's OnClickListener, if it is defined. Performs all normal
* actions associated with clicking: reporting accessibility event, playing
* a sound, etc.
*
* @return True there was an assigned OnClickListener that was called, false
* otherwise is returned.
*/
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
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;
}
結(jié)論
- Activity和View中沒(méi)有OnInterceptTouchEvent方法,只有ViewGroup才有
- 分發(fā)過(guò)程由上到下滞磺,Activity->Window(PhoneWindow)->DecorView->ViewGroup->View,處理過(guò)程由下到上升薯,View->ViewGroup->DecorView->Window(PhoneWindow)->Activity,如果分發(fā)(處理)過(guò)程中有View/ViewGroup消耗事件[返回true]則事件不會(huì)往下傳遞(往上傳遞)
- 事件分發(fā)序列是有一個(gè)ACTION_DOWN,零或多個(gè)ACTION_MOVE击困,單個(gè)ACTION_UP組成,即ACTION_DOWN->[ACTION_MOVE->...->ACTION_MOVE->]ACTION_UP
- ViewGroup的ACTION_DOWN事件必定調(diào)用OnInterceptTouchEvent涎劈,如果攔截了ACTION_DOWN事件則后續(xù)的事件序列都不會(huì)再調(diào)用OnInterceptTouchEvent, 事件都由該ViewGroup處理,ViewGroup的Child也不會(huì)再收到后續(xù)的事件序列
- 如果ViewGroup在ACTION_MOVE中攔截事件阅茶,則會(huì)走到dispatch(ev,true,target.child,target.pointIdBits)中蛛枚,在該方法中child會(huì)收到一個(gè)ACTION_CANCEL事件,ViewGroup不處理該事件脸哀,最終蹦浦,mFirstTouchTarget置為null,從下個(gè)事件開(kāi)始都交由ViewGroup處理
- 子類可以通過(guò)調(diào)用的父類的requestDisallowInterceptTouchEvent來(lái)改變父類是否攔截事件撞蜂,但是如果ACTION_DOWN事件已被父類攔截盲镶,則無(wú)法改變;且ACTION_DOWN事件不受該方法標(biāo)志位FLAG_DISALLOW_INTERCEPT控制,因?yàn)閂iewGroup的disptachTouchEvent方法在收到ACTION_DOWN事件時(shí)會(huì)調(diào)用resetTouchState方法重置該標(biāo)志位
- 如果child不消耗ACTION_DOWN,即dispatchTouchEvent返回false蝌诡,則后續(xù)的事件序列都由其父ViewGroup處理溉贿,調(diào)用View#dispatchTouchEvent
- 如果child不消耗ACTION_DOWN除外的事件,則該事件消失送漠,不會(huì)回傳給父ViewGroup顽照,最終會(huì)傳給Activity的onTouchEvent,但是后續(xù)的事情此child也能收到
- View#disptachTouchEvent中首先會(huì)判斷是否有設(shè)置OnTouchListener闽寡、控件enable且onTouch返回true代兵,滿足條件則事件分發(fā)完成,否則會(huì)繼續(xù)調(diào)用View#onTouchEvent
- View#onTouchEvent中爷狈,即使該View不是enable的植影,但是其是clickable、longClickable或者contextClickable的則也消耗事件涎永,如果View是enable的思币,則根據(jù)時(shí)間判斷是執(zhí)行performClick還是performLongClick,可點(diǎn)擊的View的onTouchEvent默認(rèn)返回true羡微,如Button谷饿,不可點(diǎn)擊的則返回false,如TextView和ImageView
- View方法調(diào)用順序: dispatchTouchEvent->mOnTouchListener#onTouch->onTouchEvent->performLongClick->performClick
- ViewGroup攔截ACTION_DOWN:dispatchTouchEvent->onInterceptTouchEvent->super.disptachTouchEvent妈倔,后續(xù)事件: dispatchTouchEvent->super.disptachTouchEvent
- ViewGroup不攔截ACTION_DOWN: child消耗ACTION_DOWN, dispatchTouchEvent->onInterceptTouchEvent->child#disptachTouchEvent->,后續(xù)事件事件dispatchTouchEvent->onInterceptTouchEvent->child#disptachTouchEvent->;child不消耗ACTION_DOWN博投,dispatchTouchEvent->onInterceptTouchEvent->child#disptachTouchEvent->super.disptachTouchEvent,后續(xù)事件
dispatchTouchEvent->super.disptachTouchEvent - ViewGroup攔截ACTION_MOVE: dispatchTouchEvent->onInterceptTouchEvent->child#dispatchTouchEvent(ACTION_CANCEL),后續(xù)事件disptachTouchEvent->super.dispatchTouchEvent
參考文獻(xiàn)
-
Android事件分發(fā)機(jī)制完全解析盯蝴,帶你從源碼的角度徹底理解(上) ,
Android事件分發(fā)機(jī)制完全解析毅哗,帶你從源碼的角度徹底理解(下) - 圖解 Android 事件分發(fā)機(jī)制
- 十分鐘徹底弄明白 View 事件分發(fā)機(jī)制
- Android View事件分發(fā)機(jī)制源碼分析
- Android事件傳遞機(jī)制
- View 的事件分發(fā)機(jī)制
- 安卓自定義View進(jìn)階-事件分發(fā)機(jī)制原理,安卓自定義View進(jìn)階-事件分發(fā)機(jī)制詳解
- Activity, Window, PhoneWindow,ViewGroup,View,MotionEvent
- 《Android開(kāi)發(fā)藝術(shù)探索》第三章View事件分發(fā)機(jī)制