View的事件处理
1.现象
我们分别创建一个ImageView和一个Button,并监听其onTouchListener事件。
我认为所谓能响应事件,简单地理解就是说能监听到事件的发生,判断能否监听到事件的依据就是能否调用到相应的回调函数。
实验代码
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); ImageView iv = (ImageView) findViewById(R.id.iv); iv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { System.out.println("***********iv onTouch ** "+event.getAction()+" *********"); return false; //ImageView返回false:只能响应第一个事件,之后的事件不会响应 //return true; //ImageView返回true:一直响应各种事件 } }); btn.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { System.out.println("***********btn onTouch ** "+event.getAction()+" *********"); return false; //button都能响应 //return true; //button都能响应 } });
现在ImageView的onTouch方法不同返回值响应事件的结果是不一样的,但是Button的却一样。
2.View的事件处理函数
dispatchTouchEvent 事件处理关键函数
/** * Pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event The motion event to be dispatched. * @return True if the event was handled by the view, false otherwise. 返回true事件将被本view处理 */ public boolean dispatchTouchEvent(MotionEvent event) { if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onTouchEvent(event, 0); } if (onFilterTouchEventForSecurity(event)) { //noinspection SimplifiableIfStatement ListenerInfo li = mListenerInfo; //1.判断是否传递进了实现mOnTouchListener的类(也就是是否设置了Touch监听),如果没有传,直接跳到后面 //2.判断当前控件是否可用(是否为enable) //3.传入实现类中的onTouch是否为true //三条都满足,直接返回ture,当前控件响应事件。 /*另外,此处会调用一次onTouch方法进行判断返回值,所以无论返回值是什么,第一次 点击的事件(ACTION_DOWN总会被响应),但是如果返回true怎么连续响应事件还不清楚 */ if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { return true; } //如果上述判断条件有没有满足的,则执行onTouchEven方法 //另外要说的一点,如果我们要禁止当前控件响应任何事件, //直接不做监听(上面判断第一条为false),重写onTouchEvent并直接返回false, //那么dispatchTouchEvent永远为false,当前控件不响应任何事件 //onTouchEvent源码在下面 if (onTouchEvent(event)) { return true; } } if (mInputEventConsistencyVerifier != null) { mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); } return false; }
onTouchEvent
/** * Implement this method to handle touch screen motion events. * * @param event The motion event. * @return True if the event was handled, false otherwise. */ public boolean onTouchEvent(MotionEvent event) { final int viewFlags = mViewFlags; if ((viewFlags & ENABLED_MASK) == DISABLED) { if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. return (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } /* 此处需要注意,当前控件必须是CLICKABLE的才能进入,进入之后返回的都是true,这样调用它的 dispatchTouchEvent函数返回true,否则dispatchTouchEvent函数返回false。 */ if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { switch (event.getAction()) { case MotionEvent.ACTION_UP: boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { // take focus if we don't have it already and we should in // touch mode. boolean focusTaken = false; if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { focusTaken = requestFocus(); } if (prepressed) { // The button is being released before we actually // showed it as pressed. Make it show the pressed // state now (before scheduling the click) to ensure // the user sees it. setPressed(true); } if (!mHasPerformedLongPress) { // This is a tap, so remove the longpress check removeLongPressCallback(); // Only perform take click actions if we were in the pressed state if (!focusTaken) { // Use a Runnable and post this rather than calling // performClick directly. This lets other visual state // of the view update before click actions start. if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { /************************************************ 下面这个函数会调用OnClickListener()中的onClick方法,从而实现点击回调 ************************************************/ performClick(); } } } if (mUnsetPressedState == null) { mUnsetPressedState = new UnsetPressedState(); } if (prepressed) { postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!post(mUnsetPressedState)) { // If the post failed, unpress right now mUnsetPressedState.run(); } removeTapCallback(); } break; case MotionEvent.ACTION_DOWN: mHasPerformedLongPress = false; if (performButtonActionOnTouchDown(event)) { break; } // Walk up the hierarchy to determine if we're inside a scrolling container. boolean isInScrollingContainer = isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for // a short period in case this is a scroll. if (isInScrollingContainer) { mPrivateFlags |= PFLAG_PREPRESSED; if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true); checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); break; case MotionEvent.ACTION_MOVE: final int x = (int) event.getX(); final int y = (int) event.getY(); // Be lenient about moving outside of buttons if (!pointInView(x, y, mTouchSlop)) { // Outside button removeTapCallback(); if ((mPrivateFlags & PFLAG_PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); setPressed(false); } } break; } return true; } return false; }
结论
根据上面的dispatchTouchEvent函数,我们可以发现,如果一个控件可点击(实现了
监听onClickEvent就可以置位可点击标志),那么无论onTouc返回什么内容,最终
dispatchTouchEvent函数可以都响应事件。
如果不可点击,那么onTouchEvent函数必定会返回false,只能寄希望于onTouch函数了,onTouch必
须由接口传入并且
返回true才能保证dispatchTouchEvent函数返回true,才能响应事件。
现在我们为上位的iv设置一个setOnClickListener方法,传入一个OnClickListener,这样即使
iv的onTouch返回false,也一样可以进入下面的onTouchEvent函数,并在这个函数中让返回值变为
true。
iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("***********iv OnClickListener ***********"); //鼠标弹起时候被触发 } });
ViewGroup 的事件处理与传递
ViewGroup中会重写dispatchTouchEvent函数,可以说此时dispatchTouchEvent函数是用来传递事
件的,那么谁来处理事件呢?先看一下ViewGroup中dispatchTouchEvent做了些什么。
ViewGroup的事件处理函数
dispatchTouchEvent
@Override public boolean dispatchTouchEvent(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; if (!disallowIntercept) { /********************************************************** 此处调用onInterceptTouchEvent,即是否当前ViewGroup拦截事件,如果拦截,则事件由 当前ViewGroup处理,不再向下分发。 **********************************************************/ intercepted = onInterceptTouchEvent(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; /************************************************************** 如果不拦截事件(false),则进入这个if内部 如果拦截,则直接在下面调用ViewGroup的父类的dispatchTouchEvent方法,由当前ViewGrop处理事件,而不再向下传递 **************************************************************/ if (!canceled && !intercepted) { 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 (newTouchTarget == null && childrenCount != 0) { final float x = ev.getX(actionIndex); final float y = ev.getY(actionIndex); // Find a child that can receive the event. // Scan children from front to back. final View[] children = mChildren; final boolean customOrder = isChildrenDrawingOrderEnabled(); /**************************************************************** 遍历ViewGroup中的每个子控件,看看这个事件落到谁的头上 ****************************************************************/ for (int i = childrenCount - 1; i >= 0; i--) { final int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = children[childIndex]; if (!canViewReceivePointerEvents(child) || !isTransformedTouchPointInView(x, y, child, null)) { continue; } newTouchTarget = getTouchTarget(child); 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); /*************************************************************** dispatchTransformedTouchEvent函数中调用dispatchTouchEvent,相当于递归 调用dispatchTouchEvent,查找当前孩子的子控件。 ***************************************************************/ if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { // Child wants to receive touch within its bounds. mLastTouchDownTime = ev.getDownTime(); mLastTouchDownIndex = childIndex; 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. /************************************************************************** 如果当前ViewGrop的孩子没有控件可以响应事件,那么当前ViewGrop只能调用他父类的 dispatchTouchEvent去进行响应。可以看出ViewGroup的dispatchTouchEven方法只是 进行传递,而真正是否能响应事件还是需要用View的dispatchTouchEvent的返回值。 **************************************************************************/ handled = dispatchTransformedTouchEvent(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 (dispatchTransformedTouchEvent(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; } ###onInterceptTouchEvent 是否拦截事件 public boolean onInterceptTouchEvent(MotionEvent ev) { return false; }
结论
ViewGroup的事件传递是从外部向内部传递的。 其中每一级可以调用onInterceptTouchEvent(true)拦截事件,
让当前的ViewGroup处理。如果不拦截,则会递归到最下面的控件,如果它可以处理这个事件,就处理
(dispatchTouchEvent返回true),否则还会交还给父ViewGroup。这时,递归会出来,从而调用父ViewGroup的
父类的dispatchTouchEvent方法,尝试处理事件。