Android 点击事件传递(简单版)

废话

Android点击事件的传递应该是属于“必考题”这一类型的了, 当然了解这一块对于平常开发也非常的有用。例如:滚动事件冲突的解决、自定义控件点击效果等。本篇就简单的来捋一下 Android的点击事件

先说结论

  • 在控件内传递的方式 都是 Dispatch-> Intercept(ViewGroup) ->Touch
  • onTouchEvent方法是在 dispatchTouchEvent中执行的,如果不执行super.dispatchTouchEvent 那么onTouchEvent中是不会接收到任何事件
  • ACTION_DOWN事件如果没有消费,那么ACTION_UP也不会给你机会消费
  • View不可点击,在onTouchEvent 和 dispatchTouchEvent 返回了true进行消费也不会走进来

解析

先上原型图

原型.png

Demo很简单,就是最外层是一个Activity 然后自定了一个ViewGroup 和 View

View

不可点击
通过Log可以看出 ACTION_DOWN 事件是从 Activity->ViewGroup->View->ViewGroup->Activity 中间没有事件消费 所以又返回到了Activity。 由于ACTION_DOWN事件没有消费 所以ACTION_UP不会再给你消费的机会

I: ACTIVITY  dispatchTouchEvent:     action = ACTION_DOWN
I:    GROUP  dispatchTouchEvent:     action = ACTION_DOWN
I:    GROUP  onInterceptTouchEvent:  action = ACTION_DOWN
I:     VIEW  dispatchTouchEvent:     action = ACTION_DOWN
I:     VIEW  onTouchEvent:           action = ACTION_DOWN
I:    GROUP  onTouchEvent:           action = ACTION_DOWN
I: ACTIVITY  onTouchEvent:           action = ACTION_DOWN
I: ACTIVITY  dispatchTouchEvent:     action = ACTION_UP
I: ACTIVITY  onTouchEvent:           action = ACTION_UP

可点击 其他没有任何操作
根据Log可以看出事件是从最外层传入最底层,当最底层的View给消费后将不再返回

I: ACTIVITY  dispatchTouchEvent:     action = ACTION_DOWN
I:    GROUP  dispatchTouchEvent:     action = ACTION_DOWN
I:    GROUP  onInterceptTouchEvent:  action = ACTION_DOWN
I:     VIEW  dispatchTouchEvent:     action = ACTION_DOWN
I:     VIEW  onTouchEvent:           action = ACTION_DOWN
I: ACTIVITY  dispatchTouchEvent:     action = ACTION_UP
I:    GROUP  dispatchTouchEvent:     action = ACTION_UP
I:    GROUP  onInterceptTouchEvent:  action = ACTION_UP
I:     VIEW  dispatchTouchEvent:     action = ACTION_UP
I:     VIEW  onTouchEvent:           action = ACTION_UP
I:     VIEW  onClick

ViewGroup

InterceptTouchEvent ACTION_DOWN返回为false,ACTION_UP 返回为true ,则View的 dispatchTouchEvent 和 TouchEvent会调用 ACTION_CANCEl

I: ACTIVITY  dispatchTouchEvent:    action = ACTION_DOWN
I:    GROUP  dispatchTouchEvent:    action = ACTION_DOWN
I:    GROUP  onInterceptTouchEvent: action = ACTION_DOWN
I:     VIEW  dispatchTouchEvent:    action = ACTION_DOWN
I:     VIEW  onTouchEvent:          action = ACTION_DOWN
I: ACTIVITY  dispatchTouchEvent:    action = ACTION_UP
I:    GROUP  dispatchTouchEvent:    action = ACTION_UP
I:    GROUP  onInterceptTouchEvent: action = ACTION_UP
I:     VIEW  dispatchTouchEvent:    action = ACTION_CANCEL
I:     VIEW  onTouchEvent:          action = ACTION_CANCEL

dispatchTouchEvent中 ACTION_DOWN 返回为false 其他返回为true

I: ACTIVITY  dispatchTouchEvent:    action = ACTION_DOWN
I:    GROUP  dispatchTouchEvent:    action = ACTION_DOWN
I: ACTIVITY  onTouchEvent:          action = ACTION_DOWN
I: ACTIVITY  dispatchTouchEvent:    action = ACTION_UP
I: ACTIVITY  onTouchEvent:          action = ACTION_UP

附上Demo地址:https://github.com/i-show/demos-AndroidView

你可能感兴趣的:(Android 点击事件传递(简单版))