Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 細說Android事件傳遞機制(dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent)

細說Android事件傳遞機制(dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent)

編輯:關於Android編程

本文背景:前些天用到了之前寫的自定義圖片文字復合控件,在給他設置監聽時遇到了麻煩。雖然最後解決了問題,但發現在不重寫LinearLayout的onInterceptTouchEvent時,子ImageView、子TextView、父Linearlayout三者不同的屬性配置(android:clickable android:focuseable)會造成自定義控件onClick監聽失敗、或成功。復寫了父Linearlayout 的onInterceptTouchEvent時,監聽不受子圖片、子文字的屬性影響。為知其所以然,深入研究android的事件傳遞機制,記錄於此。

一、View的dispatchTouchEvent和onTouchEvent

探討Android事件傳遞機制前,明確android的兩大基礎控件類型:View和ViewGroup。View即普通的控件,沒有子布局的,如Button、TextView. ViewGroup繼承自View,表示可以有子控件,如Linearlayout、Listview這些。而事件即MotionEvent,最重要的有3個:(1)MotionEvent.ACTION_DOWN 按下View,是所有事件的開始(2)MotionEvent.ACTION_MOVE 滑動事件
(3)MotionEvent.ACTION_UP 與down對應,表示抬起
另外,明確事件傳遞機制的最終目的都是為了觸發執行View的點擊監聽和觸摸監聽: ******.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(tag, "testLinelayout---onClick...");
}
});

*******.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub

return false;
}
});
我們簡稱為onClick監聽和onTouch監聽,一般程序會注冊這兩個監聽。從上面可以看到,onTouch監聽裡默認return false。不要小看了這個return false,後面可以看到它有大用。 對於View來說,事件傳遞機制有兩個函數:dispatchTouchEvent負責分發事件,在dispatch***裡又會調用onTouchEvent表示執行事件,或者說消費事件,結合源碼分析其流程。事件傳遞的入口是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.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }

            if (onTouchEvent(event)) {
                return true;
            }
        }

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false;
    }
找到這個判斷: if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
return true;
}
他會執行View的OnTouchListener.onTouch這個函數,也就是上面說的onTouch監聽。裡面有三個判斷,如果三個都為1,就會執行return true,不往下走了。而默認的onTouch監聽返回false,只要一個是false,就不會返回true。接著往下看,程序執行onTouchEvent:
            if (onTouchEvent(event)) {
                return true;
            }
onTouchEvent的源碼比較多,貼最重要的:
                        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)) {
                                    performClick();
                                }
                            }
                        }
可以看到有個performClick(),它的源碼裡有這麼一句 li.mOnClickListener.onClick(this);
    public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            return true;
        }

        return false;
    }

終於對上了,它執行了我們注冊的onClick監聽。當然執行前會經過一系列判斷,是否注冊了監聽等。
總結:1、事件入口是dispatchTouchEvent(),它會先執行注冊的onTouch監聽,如果一切順利的話,接著執行onTouchEvent,在onTouchEvent裡會執行onClick監聽。2、無論是dispatchTouchEvent還是onTouchEvent,如果返回true表示這個事件已經被消費、處理了,不再往下傳了。在dispathTouchEvent的源碼裡可以看到,如果onTouchEvent返回了true,那麼它也返回true。如果dispatch***在執行onTouch監聽的時候,onTouch返回了true,那麼它也返回true,這個事件提前被onTouch消費掉了。就不再執行onTouchEvent了,更別說onClick監聽了。3、我們通常在onTouch監聽了設置圖片一旦被觸摸就改變它的背景、透明度之類的,這個onTouch表示事件的時機。而在onClick監聽了去具體干某些事。
下面通過代碼來說明,自定義一個TestButton繼承自Button,重寫它的dispath***和onTouchEvent方法,為了簡單只關注down和up事件。
package org.yanzi.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

public class TestButton extends Button {
	private final static String tag = "yan";
	public TestButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "TestButton-onTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "TestButton-onTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.onTouchEvent(event);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		
		return super.dispatchTouchEvent(event);
	}

}

在Activity裡注冊兩個監聽:
		testBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i(tag, "testBtn---onClick...");
			}
		});
		testBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
					break;
				case MotionEvent.ACTION_UP:
					Log.i(tag, "testBtn-onTouch-ACTION_UP...");
					break;
				default:break;

				}
				return false;
			}
		});

同時復寫Activity的dispatch方法和onTouchEvent方法:
@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		switch(ev.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "MainActivity-onTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "MainActivity-onTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.onTouchEvent(event);
	}

最終一次點擊,打印信息如下: Line 33: 01-08 14:59:45.847 I/yan ( 4613): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 35: 01-08 14:59:45.849 I/yan ( 4613): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 37: 01-08 14:59:45.849 I/yan ( 4613): testBtn-onTouch-ACTION_DOWN...
Line 39: 01-08 14:59:45.849 I/yan ( 4613): TestButton-onTouchEvent-ACTION_DOWN...
Line 41: 01-08 14:59:45.939 I/yan ( 4613): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 43: 01-08 14:59:45.941 I/yan ( 4613): TestButton-dispatchTouchEvent-ACTION_UP...
Line 45: 01-08 14:59:45.944 I/yan ( 4613): testBtn-onTouch-ACTION_UP...
Line 47: 01-08 14:59:45.946 I/yan ( 4613): TestButton-onTouchEvent-ACTION_UP...
Line 49: 01-08 14:59:45.974 I/yan ( 4613): testBtn---onClick...
事件先由Activity的dispatchTouchEvent進行分發,然後TestButton的dispatchTouchEvent進行分發,接著執行onTouch監聽,然後執行onTouchEvent。第二次UP動作的時候,在onTouchEvent裡又執行了onClick監聽。 如果我們想這個TestButton只能執行onTouch監聽不能執行onClick監聽,方法有很多。在onTouch監聽裡默認返回false改為true,如下:
testBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
					break;
				case MotionEvent.ACTION_UP:
					Log.i(tag, "testBtn-onTouch-ACTION_UP...");
					break;
				default:break;

				}
				return true;
			}
		});

事件流程為: Line 75: 01-08 15:05:51.627 I/yan ( 5262): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 77: 01-08 15:05:51.628 I/yan ( 5262): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 79: 01-08 15:05:51.629 I/yan ( 5262): testBtn-onTouch-ACTION_DOWN...
Line 81: 01-08 15:05:51.689 I/yan ( 5262): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 83: 01-08 15:05:51.691 I/yan ( 5262): TestButton-dispatchTouchEvent-ACTION_UP...
Line 85: 01-08 15:05:51.695 I/yan ( 5262): testBtn-onTouch-ACTION_UP...
可以看到壓根就沒執行onTouchEvent。因為onTouch返回了true,已提前將這個事件消費了,就不往下傳了,dispatch流程提前終止。

二、ViewGroup的dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent

再來看ViewGroup,在復寫ViewGroup時可以發現它的onTouchEvent在在View裡的,表示這兩個方法是一樣的。但dispatchTouchEvent是在ViewGroup裡的,表示和View的dispatchTouchEvent不一樣,多了一個onInterceptTouchEvent函數,表示攔截的意思。鏈接 打個很形象的比喻,這玩意就像個秘書、謀士。為啥View沒有呢,因為它級別不夠,一個Button裡面是不可能有子View的。但LinearLayout(繼承ViewGroup)就有孩子(子布局),這個onInterceptTouchEvent就會判斷事件要不要通知它的孩子呢。它的源碼如下:
    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) {
                    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;
            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 (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);

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        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);
                            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.
                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;
    }

可以看到標紅的有兩句(intercepted = onInterceptTouchEvent(ev); if (!canceled && !intercepted) ),它會先調用 intercepted = onInterceptTouchEvent(ev);然後通過if判斷。
  public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

它就一句話,默認false。也就是說這個謀士默認的意見是,永遠不攔截!!!!只要有孩子,就交給孩子們處理吧。下面給出實例說明,新建TestLinearLayout繼承自Linearlayout。
package org.yanzi.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;

public class TestLinearLayout extends LinearLayout{
	private final static String tag = "yan";
	public TestLinearLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		switch(ev.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		switch(ev.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_DOWN...");
			break;
		case MotionEvent.ACTION_UP:
			Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_UP...");
			break;
		default:break;
		}
		return super.onTouchEvent(event);
	}
	

}
布局文件改成:


    

    

        
    


在Activity裡給這個自定義LinearLayout也注冊上onClick監聽、onTouch監聽。
testLinelayout = (TestLinearLayout)findViewById(R.id.linearlayout_test);
		testLinelayout.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch(event.getAction()){
				case MotionEvent.ACTION_DOWN:
					Log.i(tag, "testLinelayout-onTouch-ACTION_DOWN...");
					break;
				case MotionEvent.ACTION_UP:
					Log.i(tag, "testLinelayout-onTouch-ACTION_UP...");
					break;
				default:break;

				}
				return false;
			}
		});
		
		testLinelayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i(tag, "testLinelayout---onClick...");
			}
		});

不復寫事件傳遞裡的 任何方法,流程如下: Line 57: 01-08 15:29:42.167 I/yan ( 5826): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 59: 01-08 15:29:42.169 I/yan ( 5826): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 61: 01-08 15:29:42.169 I/yan ( 5826): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 63: 01-08 15:29:42.169 I/yan ( 5826): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 65: 01-08 15:29:42.170 I/yan ( 5826): testBtn-onTouch-ACTION_DOWN...
Line 67: 01-08 15:29:42.170 I/yan ( 5826): TestButton-onTouchEvent-ACTION_DOWN...---------------------------------------------------------------------------------------------------------------------------
Line 69: 01-08 15:29:42.279 I/yan ( 5826): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 71: 01-08 15:29:42.280 I/yan ( 5826): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 73: 01-08 15:29:42.283 I/yan ( 5826): TestLinearLayout-onInterceptTouchEvent-ACTION_UP...
Line 75: 01-08 15:29:42.287 I/yan ( 5826): TestButton-dispatchTouchEvent-ACTION_UP...
Line 81: 01-08 15:29:42.298 I/yan ( 5826): testBtn-onTouch-ACTION_UP...
Line 83: 01-08 15:29:42.301 I/yan ( 5826): TestButton-onTouchEvent-ACTION_UP...
Line 85: 01-08 15:29:42.313 I/yan ( 5826): testBtn---onClick...

由Activity的dispatchTouchEvent----Linearlayout的dispatchTouchEvent------------問問它的謀士要不要讓孩子知道onInterceptTouchEvent---------孩子的dispatchTouchEvent-----孩子的onTouch監聽------孩子的onTouchEvent----孩子的onClick監聽。為了更清晰這個流程,下面作如下改動:1、如果事件傳給了孩子們,但孩子沒有onTouch和onClick監聽怎麼辦?即將button的onclick和onTouch都注釋掉:流程如下: Line 131: 01-08 15:36:16.574 I/yan ( 6124): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 133: 01-08 15:36:16.574 I/yan ( 6124): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 135: 01-08 15:36:16.574 I/yan ( 6124): TestButton-dispatchTouchEvent-ACTION_DOWN...
Line 137: 01-08 15:36:16.575 I/yan ( 6124): TestButton-onTouchEvent-ACTION_DOWN...
Line 143: 01-08 15:36:16.746 I/yan ( 6124): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 145: 01-08 15:36:16.747 I/yan ( 6124): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 147: 01-08 15:36:16.747 I/yan ( 6124): TestLinearLayout-onInterceptTouchEvent-ACTION_UP...
Line 149: 01-08 15:36:16.748 I/yan ( 6124): TestButton-dispatchTouchEvent-ACTION_UP...
Line 151: 01-08 15:36:16.748 I/yan ( 6124): TestButton-onTouchEvent-ACTION_UP...
因為事件給了孩子們,它沒監聽也關系不到父親了,父親的onClick和onTouch都沒執行。2,如果將TestLinearlayout的onInterceptTouchEvent 改成return true,即不讓孩子們知道。 Line 57: 01-08 15:40:06.832 I/yan ( 6640): MainActivity-dispatchTouchEvent-ACTION_DOWN...
Line 59: 01-08 15:40:06.835 I/yan ( 6640): TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...
Line 61: 01-08 15:40:06.836 I/yan ( 6640): TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...
Line 63: 01-08 15:40:06.836 I/yan ( 6640): testLinelayout-onTouch-ACTION_DOWN...
Line 65: 01-08 15:40:06.836 I/yan ( 6640): TestLinearLayout-onTouchEvent-ACTION_DOWN...
Line 67: 01-08 15:40:07.016 I/yan ( 6640): MainActivity-dispatchTouchEvent-ACTION_UP...
Line 69: 01-08 15:40:07.017 I/yan ( 6640): TestLinearLayout-dispatchTouchEvent-ACTION_UP...
Line 73: 01-08 15:40:07.025 I/yan ( 6640): testLinelayout-onTouch-ACTION_UP...
Line 75: 01-08 15:40:07.026 I/yan ( 6640): TestLinearLayout-onTouchEvent-ACTION_UP...
Line 77: 01-08 15:40:07.052 I/yan ( 6640): testLinelayout---onClick...
果然事件就此打住,孩子們壓根不知道,父親執行了onClick和onTouch監聽。可見父親還是偉大的啊,只要謀士不攔截事件,那麼事件就給孩子。 最後的結論:1、如果是自定義復合控件,如圖片+文字,我再Activity裡給你注冊了onClick監聽,期望點擊它執行。那麼最簡單的方法就是將圖片+文字的父布局,也即讓其容器ViewGroup的秘書將事件攔下,這樣父親就可以執行onClick了。這時候的父親就像一個獨立的孩子一樣了(View),無官一身輕,再也不用管它的孩子了,可以正常onClick onTouch.2、如果希望一個View只onTouch而不onClick,在onTouch裡return true就ok了。3、dispatch是為了onTouch監聽,onTouchEvent是為了onClick監聽。4、自定義布局時,一般情況下:@Override
public boolean onTouchEvent(MotionEvent event) {return super.onTouchEvent(event);}

@Override
public boolean dispatchTouchEvent(MotionEvent event) {return super.dispatchTouchEvent(event);
我們可以復寫,但是最後的super.***是萬萬不能少滴。如果少了,表示連dispatch*** onTouchEvent壓根就不調用了,事件就此打住。 貌似真相水落石出了,但究竟清楚了沒有請看下篇根據自定義復合控件的監聽問題再探討下。
參考: 鏈接1 (灰常感謝前輩的大作啊) 鏈接2測試代碼: http://download.csdn.net/detail/yanzi1225627/7121063
---------------------------本文系原創,轉載注明作者:yanzi1225627

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved