1. 程式人生 > >Android touch 事件分發 (一)Activity dispatchTouchEvent

Android touch 事件分發 (一)Activity dispatchTouchEvent

/**
	 * You can override this to intercept all touch screen events before they are dispatched to the window <br>
	 * 
	 * @return false|true 無論返回true|false方法會被攔截。onTouchEvent 不會執行此時Activity中的所有view都沒法獲取focus <br>
	 * 
	 *         返回 super.dispatchTouchEvent() 將會呼叫onTouchEvent
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		d("touch---dispatch", "" + ev.getAction());
		if (returnValue == null) {
			// getWindow().superDispatchTouchEvent(ev);
			return super.dispatchTouchEvent(ev);
		} else {
			return returnValue;
		}
	}



	@Override
	public boolean onTouchEvent(MotionEvent ev) {

		d("touch---", "" + ev.getAction());

		return true;
	}

如果想攔截Activity中所有的touch事件,則覆蓋改dispatchTouchEvent方法,並且return false 或者 true

只有呼叫super.dispatchTouchEvent()的時候,才有可能呼叫onTouchEvent

以下是Activity類中dispatchTouchEvent的定義

/**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }