Android中的事件分发传递机制
##实例代码
参照如下的布局来说明Android的事件传递机制`
`
实例代码的解释
上面的布局为在RelativeLayout中有一个子控件LinearLayout,在LinearLayout中有一个字控件Button当Activity获取到事件后,会调用它的dispathTouchEvent()来分发事件到RelativeLayout(即最外层的ViewGroup)的dispathTouchEvent()
实例代码中事件的传递过程
事件从层层往下传递的过程及其回调的方法
RelativeLayout的dispathTouchEvent()接受到事件后。会调用自己的OnInterceptTouchEvent()方法,如果OnInterceptTouchEvent()返回为true,表示RelativeLayout需要这个事件, 然后回去调用自己的OnTouchEvent()方法来处理事件,事件到此结束, 如果RelativeLayout的OnInterceptTouchEvent()返回为false,则会继续吧事件传递到LinearLayout 的dispathTouchEvent()方法,
在LinearLayout 的dispathTouchEvent()方法中也会先去调用自己的OnInterceptTouchEvent()方法,
如果OnInterceptTouchEvent()返回为true,表示LinearLayout需要这个事件, 然后回去调用自己的OnTouchEvent()方法来处理事件,事件到此结束, 如果LinearLayout的OnInterceptTouchEvent()返回为false,则会继续吧事件传递到Button的dispathTouchEvent()方法,
Button接受到这个事件后,应为Button是View(LinearLayout/RelativeLayout为ViewGroup),所以它没有子控件,所以它也没有OnInterceptTouchEvent(),Button的dispathTouchEvent()方法会直接调用OnTouchEvent()方法,如果该方法返回为true,则表示Button需要这个方法, 事件到此结束, 如过Button的OnTouchEvent()方法也返回为false,则Button事件会继续往回传。
事件到View控件后,没有得到消费,继续往回传的过程及其回调的方法
当Button的OnTouchEvent()方法也返回为false,则事件传回到LinearLayout的dispathTouchEvent()方法中,该方法不会再去调OnInterceptTouchEvent(),而是直接去掉它的OnTouchEvent()方法,如果OnTouchEvent()返回为true,则事件结束,如果返回为false,则事件继续往上传,
到达RelativeLayout的dispathTouchEvent(),同LinearLayout一样,它回去直接调用OnTouchEvent()方法。如果OnTouchEvent()返回为true,则事件结束,如果返回为false,则继续上传带Activity的dispathTouchEvent()方法,
Activity的dispathTouchEvent()直接调用自己的OnTouchEvent方法,如果OnTouchEvent()方法为true,则事件结束,如果返回为false,则事件丢失,则也结束。
更多相关文章
- Android获取本机IP地址(不是localhost)和MAC的方法
- android中SeekBar拖动进度条的使用及事件监听
- Android 导入android源码有错,R.java文件不能自动生成解决方法
- Git,SVN使用方法杂记(更新中)
- 解决develop.android.com无法访问到最佳方法
- android软键盘enter键的替换与事件监听
- Android ActionBar使用方法(二)
- Android dex ,xml 文件反编译方法