现在的位置: 首页 > 移动开发 > 正文

Android touch 事件分发 (一)Activity dispatchTouchEvent

2019年10月09日 移动开发 ⁄ 共 1172字 ⁄ 字号 评论关闭
/**
	 * 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);
    }

抱歉!评论已关闭.