View的事件分发机制简述

本文详细解析了Android中点击事件的分发流程,包括dispatchTouchEvent、onInterceptTouchEvent及onTouchEvent三个关键方法的作用与交互方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


要分析的对象就是MotionEvent,点击事件的事件分发其实就是对MotionEvent事件的分发过程,当MotionEvent产生后,系统需要把这个事件传递给一个具体的View,这个传递过程就是分发过程。这个过程由三个很重要的方法共同完成:

dispatchTouchEvent,onInterceptTouchEvent,onTouchEvent。 


1、public boolean dispatchTouchEvent(MotionEvent ev) 

进行事件分发。

Pass the touch screen motion event down to the target view, or this view if it is the target.
Parameters
ev	The motion event to be dispatched.
Returns

True if the event was handled by the view, false otherwise.


2、public boolean onInterceptTouchEvent(MotionEvent ev)

Added in API level 1
Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.
Parameters
ev	The motion event being dispatched down the hierarchy.
Return true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.

在dispatchTouchEvent方法内部调用,用来判断是否拦截某个事件,若当前View拦截了某个事件,那么在同一事件序列中,此方法不会被再次调用,返回结果表示是否拦截该事件。

3、public boolean onTouchEvent(MotionEvent event)

Added in API level 1
Implement this method to handle touch screen motion events.
If this method is used to detect click actions, it is recommended that the actions be performed by implementing and callingperformClick(). This will ensure consistent system behavior, including:
obeying click sound preferences
dispatching OnClickListener calls
handling ACTION_CLICK when accessibility features are enabled
Parameters
event	The motion event.
True if the event was handled, false otherwise.

View的onTouchEvent方法。在dispatchTouchEvent方法中调用,用来处理点击事件,返回结果表示是否消耗当前事件,若不消耗,则在同一个事件序列中View无法再次接收到事件。


上述三个方法的关系:

用伪代码表示:

 

public boolean dispatchTouchEvent(MotionEvent ev){
	boolean consume = false;
	if(onInterceptTouchEvent(ev)){
		consume = onTouchEvent(ev);
	}else{
		consume = child.dispatchTouchEvent(ev);
	}
	return consume;
}

 

由以上伪代码,点击事件的传递规则:对于一个根ViewGroup来说,点击事件产生后会首先传递给它,这是它的diapatchTouchEvent就会被调用,如果这个ViewGroup的onInterceptTouchEvent方法返回true就表示它要拦截当前事件,接着事件就交给这个ViewGroup处理;若onInterceptTouchEvent方法返回false,就表示它不拦截这个事件,这个事件将继续传递给它的子元素,接着子元素的diapatchTouchEvent方法会被调用,如此反复直到事件被处理。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值