布局文件:
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.MainActivity” >
<com.example.zhy_event03.MyButton
android:id=“@+id/id_btn”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“click me” />
最后看一眼MainActivity的代码
package com.example.zhy_event03;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class MainActivity extends Activity
{
protected static final String TAG = “MyButton”;
private Button mButton ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.id_btn);
mButton.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
int action = event.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
Log.e(TAG, “onTouch ACTION_DOWN”);
break;
case MotionEvent.ACTION_MOVE:
Log.e(TAG, “onTouch ACTION_MOVE”);
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, “onTouch ACTION_UP”);
break;
default:
break;
}
return false;
}
});
}
}
在MainActivity中,我们还给MyButton设置了OnTouchListener这个监听~
好了,跟View事件相关一般就这三个地方了,一个onTouchEvent,一个dispatchTouchEvent,一个setOnTouchListener;
下面我们运行,然后点击按钮,查看日志输出:
08-31 06:09:39.030: E/MyButton(879): dispatchTouchEvent ACTION_DOWN
08-31 06:09:39.030: E/MyButton(879): onTouch ACTION_DOWN
08-31 06:09:39.049: E/MyButton(879): onTouchEvent ACTION_DOWN
08-31 06:09:39.138: E/MyButton(879): dispatchTouchEvent ACTION_MOVE
08-31 06:09:39.138: E/MyButton(879): onTouch ACTION_MOVE
08-31 06:09:39.147: E/MyButton(879): onTouchEvent ACTION_MOVE
08-31 06:09:39.232: E/MyButton(879): dispatchTouchEvent ACTION_UP
08-31 06:09:39.248: E/MyButton(879): onTouch ACTION_UP
08-31 06:09:39.248: E/MyButton(879): onTouchEvent ACTION_UP
我有意点击的时候蹭了一下,不然不会触发MOVE,手抖可能会打印一堆MOVE的日志~~~
好了,可以看到,不管是DOWN,MOVE,UP都会按照下面的顺序执行:
1、dispatchTouchEvent
2、 setOnTouchListener的onTouch
3、onTouchEvent
下面就跟随日志的脚步开始源码的探索~
2、dispatchTouchEvent
====================
首先进入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