1. 介绍
最近项目需要处理触摸事件冲突,实际处理也遇到这样那样奇怪的问题,所以有了总结触摸事件分发流程的想法。此篇介绍View类的对于触摸事件的处理流程!

2. 源码分析
触摸事件经由ViewGroup坐标判断传递到View,首先会执行其

 public boolean dispatchTouchEvent(MotionEvent event) {        if (!onFilterTouchEventForSecurity(event)) {            return false;        }        if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&                mOnTouchListener.onTouch(this, event)) {            return true;        }        return onTouchEvent(event);    }

其中6-9行:判断是否监听了touch事件、控件是否可用,并会回调
mOnTouchListener.onTouch(this, event),如果该方法返回true,则View直接消耗掉触摸事件,否则会执行

public boolean onTouchEvent(MotionEvent event) {        final int viewFlags = mViewFlags;        if ((viewFlags & ENABLED_MASK) == DISABLED) {            // 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));        }        if (mTouchDelegate != null) {            if (mTouchDelegate.onTouchEvent(event)) {                return true;            }        }        if (((viewFlags & CLICKABLE) == CLICKABLE ||                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {            switch (event.getAction()) {                case MotionEvent.ACTION_UP:                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;                    if ((mPrivateFlags & 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 (!mHasPerformedLongPress) {                            // 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) {                            mPrivateFlags |= PRESSED;                            refreshDrawableState();                            postDelayed(mUnsetPressedState,                                    ViewConfiguration.getPressedStateDuration());                        } else if (!post(mUnsetPressedState)) {                            // If the post failed, unpress right now                            mUnsetPressedState.run();                        }                        removeTapCallback();                    }                    break;                case MotionEvent.ACTION_DOWN:                    if (mPendingCheckForTap == null) {                        mPendingCheckForTap = new CheckForTap();                    }                    mPrivateFlags |= PREPRESSED;                    mHasPerformedLongPress = false;                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());                    break;                case MotionEvent.ACTION_CANCEL:                    mPrivateFlags &= ~PRESSED;                    refreshDrawableState();                    removeTapCallback();                    break;                case MotionEvent.ACTION_MOVE:                    final int x = (int) event.getX();                    final int y = (int) event.getY();                    // Be lenient about moving outside of buttons                    int slop = mTouchSlop;                    if ((x < 0 - slop) || (x >= getWidth() + slop) ||                            (y < 0 - slop) || (y >= getHeight() + slop)) {                        // Outside button                        removeTapCallback();                        if ((mPrivateFlags & PRESSED) != 0) {                            // Remove any future long press/tap checks                            removeLongPressCallback();                            // Need to switch from pressed to not pressed                            mPrivateFlags &= ~PRESSED;                            refreshDrawableState();                        }                    }                    break;            }            return true;        }        return false;    }

其中4-9行:过滤不可用状态控件
其中11-15行:view控件mTouchDelegate,然而并没有什么卵用
其中17-18行:只针对可点击或者可以长按View进行事件判定,否则直接返回false,表示该View不会消耗掉事件,由于该返回值是在ViewGroup进行事件分发的时候使用,所以放到后续ViewGroup篇进行分析。
其中19-99行:分别针对ACTION_UP、ACTION_DOWN、ACTION_CANCEL、ACTION_MOVE进行不同的操作,同时这些操作一直围绕这个时间轴进行

  • ACTION_DOWN事件
    其中66-71行:首先对mPendingCheckForTap 判空并创建CheckForTap实例。然后标记View状态为prePressed,并将mPendingCheckForTap 投递到主线程MessageQueue消息链表中。在CheckForTap类中
private final class CheckForTap implements Runnable {        public void run() {            mPrivateFlags &= ~PREPRESSED;            mPrivateFlags |= PRESSED;            refreshDrawableState();            if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {                postCheckForLongClick(ViewConfiguration.getTapTimeout());            }        }    }

在run()方法实现中,首先将prePressed状态位归零,然后状态标记为Pressed状态,然后调用refreshDrawableState刷新View效果,如果View是可长按的,则开启长按事件监听。然后看postCheckForLongClick()方法的实现。

private void postCheckForLongClick(int delayOffset) {        mHasPerformedLongPress = false;        if (mPendingCheckForLongPress == null) {            mPendingCheckForLongPress = new CheckForLongPress();        }        mPendingCheckForLongPress.rememberWindowAttachCount();        postDelayed(mPendingCheckForLongPress,                ViewConfiguration.getLongPressTimeout() - delayOffset);    }

该方法首先创建CheckForLongPress类实例,然后以375ms的延时投递到MessageQueue消息链表中,当该Message被执行

class CheckForLongPress implements Runnable {        private int mOriginalWindowAttachCount;        public void run() {            if (isPressed() && (mParent != null)                    && mOriginalWindowAttachCount == mWindowAttachCount) {                if (performLongClick()) {                    mHasPerformedLongPress = true;                }            }        }        public void rememberWindowAttachCount() {            mOriginalWindowAttachCount = mWindowAttachCount;        }    }

会执行performLongClick()方法

/**     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the     * OnLongClickListener did not consume the event.     *     * @return True if one of the above receivers consumed the event, false otherwise.     */    public boolean performLongClick() {        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);        boolean handled = false;        if (mOnLongClickListener != null) {            handled = mOnLongClickListener.onLongClick(View.this);        }        if (!handled) {            handled = showContextMenu();        }        if (handled) {            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);        }        return handled;    }

在此方法中我们看到了针对longClick事件的回调,其返回值和上下文Menu也有关系,但与本文主题无关,有兴趣的大家可以自行分析。
然后再回头看ACTION_MOVE事件

  • ACTION_MOVE事件
    其中86-97行:以slop为为误差,检查是否move到了控件外部,假如移动到控件外部,如果View处于tap监听阶段,则移除tap监听;
    如果View处理pressed阶段,则移除长按监听,并将pressed状态为归零,同时刷新View状态效果。

  • ACTION_CANCEL事件
    其中75-78行:首先将pressed状态位归零,然后刷新View状态效果,同时移除tap检测

  • ACTION_UP事件
    ACTION_UP事件和ACTION_MOVE事件类似,可以发生在tap检测阶段也可以发生在longClick检测阶段
    其中30-46行:假如还没有执行长按事件回调则移除长按事件检测,同时对mPerformClick判空并创建PerformClick实例,在PerformClick类中
 private final class PerformClick implements Runnable {        public void run() {            performClick();        }    }

调用performClick()方法,完成对click事件的回调

 /**     * Call this view's OnClickListener, if it is defined.     *     * @return True there was an assigned OnClickListener that was called, false     *         otherwise is returned.     */    public boolean performClick() {        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);        if (mOnClickListener != null) {            playSoundEffect(SoundEffectConstants.CLICK);            mOnClickListener.onClick(this);            return true;        }        return false;    }

3. 总结
从源码可以看出,View事件的传递围绕上面的时间轴并结合prePressed、pressed状态位以及tap检测和longClick检测展开,并按照事件的类型(down、move、cancel、up)进行不同操作,理清这些状态,view触摸事件的传递流程就很清晰明了了。

更多相关文章

  1. Android开发重修
  2. ViewGroup中的onInterceptTouchEvent和onTouchEvent调用时序
  3. Android使用Fragment来实现TabHost的功能(解决切换Fragment状态不
  4. Android处理按钮重复点击事件
  5. Cordova for android如何在App中处理退出按钮事件
  6. Android(安卓)解决ListView里面多套布局多个EditText数据混乱问
  7. 学习笔记:Android基本组件之Activity
  8. Android——用XML的selector实现按钮多态
  9. Android(安卓)开发第四天

随机推荐

  1. Android之People&Roles
  2. Android AndroidStudio开发全部套件百度
  3. [转]近百android程序源码贡献
  4. Android开发笔记(二)——布局管理器
  5. Android如何在局域网中发送网络广播
  6. Android LifecycleObserver
  7. Android USB tethering相关代码
  8. 正则表达式pcre在Android下的移植
  9. ch015 Android ActivityGroup
  10. cocos2d-x android