touch event
首先,接收touch事件的是ViewGroup,然后才是其child,某个具体的view
首先触发的是ViewGroup的onInterceptTouchEvent方法
onInterceptTouchEvent (MotionEvent ev)
ViewGroup中比较特殊的一个方法。默认实现如下:
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
这个方法注释很长:
/**
* 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.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way. Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it). Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return 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.
*/
实现这个方法可以截获所有的Touch事件。这样你就可以控制向child分发的Touch事件。
一般实现这个方法,需要同时实现View.onTouchEvent(MotionEvent)方法。
事件是按照如下的顺序被接收的:
1.首先在onInterceptTouchEvent()中接收到Down事件。
2.Down事件将会:要么给这个ViewGroup的一个child view处理,要么是这个ViewGroup自己的onTouchEvent()处理。
ViewGroup自己处理意味着你应该在onTouchEvent()的实现中返回true,这样你就可以继续看到这个gesture的其他部分,如果返回false,将会返回寻找一个parent view去处理它。如果在onTouchEvent()中返回true,你将不会再在onInterceptTouchEvent()再收到接下来的事件,所有的Touch处理必须放在onTouchEvent()中正常处理。
3.如果你在onInterceptTouchEvent()中返回false,接下来的每一个事件都会先传到onInterceptTouchEvent(),之后传递到目标view的onTouchEvent()中。这里的目标可能是个子控件。
4.如果你在onInterceptTouchEvent()中返回true,将不会再接收到手势中的其他事件,当前的目标view将会接收到同一个事件,但是动作是 ACTION_CANCEL。其他所有的事件将会被直接传递到onTouchEvent()中,并且不再在onInterceptTouchEvent()中出现。
看一下ViewGroup的dispatchTouchEvent方法的源码,这个是4.0.3的源码
@Override
public boolean <strong>dispatchTouchEvent</strong>(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
<strong>if (!disallowIntercept) </strong>{
intercepted = <strong><span style="color:#ff0000;">onInterceptTouchEvent</span></strong>(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
<span style="color:#ff0000;">if (!canceled && !intercepted)</span> {//<span style="color:#cc9933;background-color: rgb(255, 255, 255);">如果没有拦截,且没有取消,交给子View</span>
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {
// Find a child that can receive the event.
// Scan children from front to back.
final View[] children = mChildren;
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
for (int i = childrenCount - 1; i >= 0; i--) {<span style="color:#ff6600;">//遍历所有的子view,找出当前点击的子view</span>
final View child = children[i];
if (!canViewReceivePointerEvents(child)
|| !<strong>isTransformedTouchPointInView</strong>(x, y, child, null)) {<span style="color:#3366ff;">//该方法计算点击点所在的子view</span>
continue;
}
<span style="color:#ff0000;"> newTouchTarget = getTouchTarget(child);</span>
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (<strong>dispatchTransformedTouchEvent</strong>(ev, false, child, idBitsToAssign)) {
<span > </span>//如果child不为空,child处理,否则super.dispatch
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = i;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = <strong>dispatchTransformedTouchEvent</strong>(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (<strong>dispatchTransformedTouchEvent</strong>(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
这段代码略复杂,主要就是看由child,还是parent处理touch事件。
如果你在执行ACTION_DOWN的时候返回了false,后面一系列其它的action就不会再得到执行了。简单的说,就是当dispatchTouchEvent在进行事件分发的时候,只有前一个action返回true,才会触发后一个action。
因为ImageView和按钮不同,它是默认不可点击的
a. onTouch和onTouchEvent有什么区别,又该如何使用?
从源码中可以看出,这两个方法都是在View的dispatchTouchEvent中调用的,onTouch优先于onTouchEvent执行。如果在onTouch方法中通过返回true将事件消费掉,onTouchEvent将不会再执行。
另外需要注意的是,onTouch能够得到执行需要两个前提条件,第一mOnTouchListener的值不能为空,第二当前点击的控件必须是enable的。因此如果你有一个控件是非enable的,那么给它注册onTouch事件将永远得不到执行。对于这一类控件,如果我们想要监听它的touch事件,就必须通过在该控件中重写onTouchEvent方法来实现。
1 Android中touch事件的传递,绝对是先传递到ViewGroup,再传递到View的。
2 在ViewGroup中可以通过onInterceptTouchEvent方法对事件传递进行拦截,onInterceptTouchEvent方法返回true代表不允许事件继续向子View传递,返回false代表不对事件进行拦截,默认返回false。
3. 子View中如果将传递的事件消费掉,ViewGroup中将无法接收到任何事件。
———————————————
@Override
//处理点击事件,如果是手势的事件则不作点击事件 普通View
//注:必须是 setClickable(true); setLongClickable(true);
public boolean performClick() {
if(isGesture){
return true;
}else{
return super.performClick();
}
}
———————
参考view的源码
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
performClick()方法,那我们进入到这个方法里瞧一瞧:
1. public boolean
2. sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3. if (mOnClickListener != null) {
4. playSoundEffect(SoundEffectConstants.CLICK);
5. this);
6. return true;
7. }
8. return false;
9. }
可以看到,只要mOnClickListener不是null,就会去调用它的onClick方法,那mOnClickListener又是在哪里赋值的呢?经过寻找后找到如下方法:
1. public void setOnClickListener(OnClickListener l) {
2. if (!isClickable()) {
3. setClickable(true);
4. }
5. mOnClickListener = l;
6. }
每当控件被点击时,都会在performClick()方法里回调被点击控件的onClick方法。
———————————
touch与click的关系
1. button.setOnClickListener(new OnClickListener() {
2. @Override
3. public void onClick(View v) {
4. Log.d("TAG", "onClick execute");
5. }
6. });
7. button.setOnTouchListener(new OnTouchListener() {
8. @Override
9. public boolean onTouch(View v, MotionEvent event) {
10. Log.d("TAG", "onTouch execute, action " + event.getAction());
11. return false;
12. }
13. });
onTouch是优先于onClick执行的
onTouch方法是有返回值的,这里我们返回的是false,如果我们尝试把onTouch方法里的返回值改成true,那么click事件不会发生。只要你触摸到了任何一个控件,就一定会调用该控件的dispatchTouchEvent方法。那当我们去点击按钮的时候,就会去调用Button类里的dispatchTouchEvent方法,可是你会发现Button类里并没有这个方法,那么就到它的父类TextView里去找一找,你会发现TextView里也没有这个方法,那没办法了,只好继续在TextView的父类View里找一找,这个时候你终于在View里找到了这个方法,
1. public boolean dispatchTouchEvent(MotionEvent event) {
2. mOnTouchListener
3. mOnTouchListener.onTouch(this, event)) {
4. return true;
5. }
6. return onTouchEvent(event);
7. }
mOnTouchListener这个变量是在哪里赋值的呢?我们寻找之后在View里发现了如下方法:
1. public void
2. mOnTouchListener = l;
3. }
找到了,mOnTouchListener正是在setOnTouchListener方法里赋值的,也就是说只要我们给控件注册了touch事件,mOnTouchListener就一定被赋值了。第三个条件就比较关键了,mOnTouchListener.onTouch(this, event),其实也就是去回调控件注册touch事件时的onTouch方法。也就是说如果我们在onTouch方法里返回true,就会让这三个条件全部成立,从而整个方法直接返回true。如果我们在onTouch方法里返回false,就会再去执行onTouchEvent(event)方法。
分析:dispatchTouchEvent中最先执行的就是onTouch方法,因此onTouch肯定是要优先于onClick执行的,也是印证了刚刚的打印结果。而如果在onTouch方法里返回了true,就会让dispatchTouchEvent方法直接返回true,不会再继续往下执行。而打印结果也证实了如果onTouch返回true,onClick就不会再执行了。同时:onClick的调用肯定是在onTouchEvent(event)方法中的
--------------
如果一个控件是可点击的,那么点击该控件时,dispatchTouchEvent的返回值必定是true。
ViewGroup的父类是View。
一般是parent的onInterceptTouchEvent返回false,这样子控件才能接收到touch事件,否则,touch被parent的dispatchTouchEvent方法捕获并处理。
--------------------