view点击事件处理过程

view过程

先自定义一个MyTextView 继承TextView 并在dispatchTouchEvent onTouchEvent打印日志

代码如下:

public class MyTextView extends TextView {

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
//        Log.e("myTextView", "myTextView dispatchTouchEvent");

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_UP");
                break;
        }

        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                Log.e("myTextView", "myTextView onTouchEvent ACTION_DOWN");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("myTextView", "myTextView onTouchEvent ACTION_MOVE");
                break;
            case MotionEvent.ACTION_UP:
                Log.e("myTextView", "myTextView onTouchEvent ACTION_UP");
                break;
        }

        return super.onTouchEvent(event);
    }
}

最后在Activity的代码如下:

public class MainActivity extends AppCompatActivity {

    private MyTextView myTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myTextView = (MyTextView) findViewById(R.id.tv_show);
        myTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("activity","activity onclick");
            }
        });
        myTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()){

                    case MotionEvent.ACTION_DOWN:
                        Log.e("activity","activity onTouch ACTION_DOWN");
                        break;

                    case MotionEvent.ACTION_MOVE:
                        Log.e("activity","activity onTouch ACTION_MOVE");
                        break;

                    case MotionEvent.ACTION_UP:
                        Log.e("activity","activity onTouch ACTION_UP");
                        break;
                }

                return false;
            }
        });
    }

}

注意事项

注意这里的View不包含ViewGroup,所以过程简单些。view是一个单独的元素,没有子元素因此无法向下传递事件,所以只能自己处理事件。

在MainActivity中,我们还给MyTextView设置了OnTouchListener、setOnClickListener 这个监听~
好了,跟View事件相关一般就这三个地方了,一个onTouchEvent,一个dispatchTouchEvent,一个setOnTouchListener和 setOnClickListener;

下面我们运行,然后点击按钮,查看日志输出:

我有意点击的时候蹭了一下,不然不会触发MOVE,手抖可能会打印一堆MOVE的日志

第一种日志输出
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onclick

第二种日志输出

25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onclick

可以看到,不管是DOWN,MOVE,UP都会按照下面的顺序执行:

  1. dispatchTouchEvent
  2. setOnTouchListener的onTouch
  3. onTouchEvent
  4. setOnClickListener的onClick

下面就跟随日志的脚步开始源码的探索

  • 首先进入的是dispatchTouchEvent方法
/**
 * 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;// 这里面集合了所有注册过来的listener,包括clickListener,touchListener 
        if (li != null && li.mOnTouchListener != null
                && (mViewFlags & ENABLED_MASK) == ENABLED// view是可点击的状态 
                && li.mOnTouchListener.onTouch(this, event)) {// 执行TouchListener.onTouch方法,并根据返回值进行判断 
            result = true;
        }

        if (!result && onTouchEvent(event)) {// 调用onTouchEvent,里面再执行onClick/onLongClick  
            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;
}

OnTouchLister中的onTouch方法返回true
我有意点击的时候蹭了一下,不然不会触发MOVE,手抖可能会打印一堆MOVE的日志

17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP

从源码可以看出,首先会先判断有没有设置OnTouchListener,如果OnTouchLister中的onTouch方法返回true,那么onTouchEevent就不会被调用,得出结论OnTouchListener的优先级高于onTouchEvent。这样做的好处就是方便外界处理点击事件。同时你会发现setOnClickListener中的onClick也没有被调用。为什么设置了OnTouchLister中的onTouch方法返回true,setOnClickListener中的onClick也没有被调用呢。

  • 接着再分析onTouchEvent的实现。
    先看当View处于不可用状态点击事件的处理过程。看下面代码就知道,不可用状态的View照样会消耗点击事件,尽管看起来不可用。
/**
 * 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();
          //不可用状态的View照样会消耗点击事件,尽管看起来不可用。
    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;
}

所以得出结论:

View 的LONG_CLICKABLE属性默认为false,而CLICKABLE属性是否为false和具体的view有关。准确来说是可点击的view其CLICKABLE为true,不可点击的view其CLICKABLE为false。比如Button是可点击的,TextView是不可点击的。通过setClickable和setLongClickable,可以分别改变View的CLICKABLE和LONG_CLICKABLE的属性。另外,setOnClickListener会自动将CLICKABLE设为true,setOnLongClickListener会自动将LONG_CLICKABLE设为true.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,951评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,606评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,601评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,478评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,565评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,587评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,590评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,337评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,785评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,096评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,273评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,935评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,578评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,199评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,440评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,163评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,133评论 2 352

推荐阅读更多精彩内容