Activity调用dispatchTouchEvent()和onTouchEvent()方法

public class MyTextView extends TextView {
	public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyTextView(Context context) {
		super(context);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			Log.e("TAG", "down");
			break;
		case MotionEvent.ACTION_UP:
			Log.e("TAG", "up");
			break;
		case MotionEvent.ACTION_MOVE:
			Log.e("TAG", "move");
			break;
		default:
			break;
		}
		return super.onTouchEvent(event);
	}
}


在Activity中有一个自定义的MyTextView,重写Activity的如下方法:

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		Log.e(MainActivity.class.getSimpleName(), "dispatchTouchEvent");
		return super.dispatchTouchEvent(ev);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.e(MainActivity.class.getSimpleName(), "onTouchEvent");
		return super.onTouchEvent(event);
	}

事件从Activity的dispatchTouchEvent()方法开始传递,当没有Activity中没有view响应此事件的时候。

07-08 15:26:59.488: E/MainActivity(28247): dispatchTouchEvent
07-08 15:26:59.488: E/TAG(28247): down
07-08 15:26:59.488: E/MainActivity(28247): onTouchEvent
07-08 15:26:59.518: E/MainActivity(28247): dispatchTouchEvent
07-08 15:26:59.518: E/MainActivity(28247): onTouchEvent
07-08 15:26:59.548: E/MainActivity(28247): dispatchTouchEvent
07-08 15:26:59.548: E/MainActivity(28247): onTouchEvent
07-08 15:26:59.548: E/MainActivity(28247): dispatchTouchEvent
07-08 15:26:59.548: E/MainActivity(28247): onTouchEvent

(1)从这里可以看到当事件没有被MyTextView消费的时候,Activity的onTouchEvent()方法被调用。

当加入了如下的代码

txt.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		if (R.id.txt == v.getId()) {
			Toast.makeText(this, "txt", 1).show();
		}
	}

输出如下:

07-08 15:39:52.613: E/MainActivity(29592): dispatchTouchEvent
07-08 15:39:52.613: E/TAG(29592): down
07-08 15:39:52.653: E/MainActivity(29592): dispatchTouchEvent
07-08 15:39:52.653: E/TAG(29592): move
07-08 15:39:52.663: E/MainActivity(29592): dispatchTouchEvent
07-08 15:39:52.663: E/TAG(29592): move
07-08 15:39:52.673: E/MainActivity(29592): dispatchTouchEvent
07-08 15:39:52.673: E/TAG(29592): up

(2)当事件被MyTextView消费了,Activity的onTouchEvent()方法将不被调用。

你可能感兴趣的:(Activity调用dispatchTouchEvent()和onTouchEvent()方法)