首页 > 技术文章 > Android TouchEvent 传递

smile365 2013-10-25 11:50 原文

dispatchTouchEvent		事件的分发操作
TouchEvent			事件处理
onInterceptTouchEvent	        事件拦截操作

在Activity与View中,TouchEvent的传递会先经过 dispatchTouchEvent,然后再到onTouchEvent
在ViewGroup中,有点特殊,在dispatchTouchEvent与onTouchEvent之间,还会经过onInterceptTouchEvent这个方法

MotionEvent.ACTION_DOWN的传递
	①Activity.dispatchTouchEvent
	②ViewGroup.dispatchTouchEvent
	③ViewGroup.onInterceptTouchEvent
	④View.dispatchTouchEvent
	⑤View.onTouchEvent (如果这里返回true,后续的MOVE,UP事件都会传递到这里处理,否则继续向下传递)
	⑥ViewGroup.onTouchEvent (如果这里返回true,后续的MOVE,UP事件会通过ViewGroup.dispatchTouchEvent都会直接传递到这里处理,不在向下传递,否则继续向下传递)
	⑦Activity.onTouchEvent (如果事件经过了GroupView,View,还是传到了这里,不管这里返回的是false还是true,后续的MOVE,UP事件都会直接通过Activity.dispatchTouchEvent传递到这里)

 dispatchTouchEvent方法测试 1

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
	return (true || false);		// 直接返回true或者false
}

经测试在dispatchTouchEvent方法,如果没有super.dispatchTouchEvent(event)也就是没有继续父类的实现,
这里返回true,那么事件都会传到这里结束。
这里返回false,事件会直接抛到上一层的onTouchEvent事件中
{ // 说明
    在Activity的dispatchTouchEvent返回false,事件直接结束
    在ViewGroup的dispatchTouchEvent返回false,事件会直接传递到Activity.onTouchEvent中
    在View的dispatchTouchEvent返回false,事件会直接传递到ViewGroup.onTouchEvent中
}

dispatchTouchEvent方法测试 2

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
	super.dispatchTouchEvent(event);
	return (true || false);		// 直接返回true或者false
}

测试在dispatchTouchEvent方法中加上super.dispatchTouchEvent(event)这一行
这里返回true,事件会像常规一样去传递,但是最终会传到这一层的onTouchEvent结束,相当于本层的onTouchEvent返回了true
这里返回false,事件会像常规一样去传递,最终于会在哪一层的onTouchEvent返回true结束,随便事件就会直接到那一层的onTouchEvent

 

ViewGroup.onInterceptTouchEvent
在这个方法中,返回true事件将会被拦截直接传递到ViewGroup的onTouchEvent中处理
在这个方法中,返回false事件向常规一样处理

 

PS:如有错误,欢迎指正,共同学习,多多交流!

9Tech

推荐阅读