Android中的事件分发传递机制

##实例代码
参照如下的布局来说明Android的事件传递机制`

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
		    xmlns:tools="http://schemas.android.com/tools"
		    android:layout_width="match_parent"
		    android:layout_height="match_parent"
     >
	<LinearLayout 
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
	    >
	    <Button 
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"/>
	</LinearLayout>
</RelativeLayout>`

实例代码的解释

上面的布局为在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,则事件丢失,则也结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值