Android View 事件分发机制 源码解析 (上)

布局文件:

<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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值