Android事件分发 ——Activity篇

版权声明:本文出自Eateeer的博客,转载必须注明出处。 https://blog.csdn.net/wl9739/article/details/51178311

在开发过程中,对于点击事件的处理是很频繁的。对于一个控件(View)来说,onClickListenr()和onTouchListener()有什么区别和联系?我们自定义了一个控件,点击自定义控件时如何不触发被它覆盖的View的点击事件?这些都和事件分发机制有关。下面就来分析一下,当一个点击事件发生时,这个事件到底是怎么溜达的?

现在让我们创建一个简单的Activity,创建一个TestLinearLayout继承自LinearLayout,创建一个Test继承自Button。

在TestLineaLayout类中,重写了和事件相关的代码,整个代码如下:

public class TestLinearLayout extends LinearLayout {

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d("TestLinerLayout", "onInterceptTouchEvent    action = " + ev.getAction());
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("TestLinerLayout", "dispatchTouchEvent    action = " + ev.getAction());
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("TestLinerLayout", "onTouchEvent    action = " + event.getAction());
        return super.onTouchEvent(event);
    }
}

在TestButton中,同样也重写的和事件分发相关的代码,整改代码如下:

public class TestButton extends Button {

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

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.i("TestButton", "dispatchTouchEvent    action = " + event.getAction());
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i("TestButton", "onTouchEvent    action = " + event.getAction());
        return super.onTouchEvent(event);
    }
}

然后是MainActivity的XML布局:

<com.wl.com.testview.TestLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:id="@+id/myLayout"
    android:orientation="vertical">

    <com.wl.com.testview.TestButton
        android:id="@+id/myButton"
        android:text="Click Me"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</com.wl.com.testview.TestLinearLayout>

最后是MainActivity的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener {

    TestButton myButton;
    TestLinearLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myButton = (TestButton) findViewById(R.id.myButton);
        linearLayout = (TestLinearLayout) findViewById(R.id.myLayout);

        myButton.setOnClickListener(this);
        myButton.setOnTouchListener(this);

        linearLayout.setOnClickListener(this);
        linearLayout.setOnTouchListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.d("MainActivity", "onClick    " + v);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.d("MainActivity", "onTouch    action = "+event.getAction() + v);
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.d("MainActivity", "dispatchTouchEvent    action = " + ev.getAction());
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("MainActivity", "onTouchEvent    action = " + event.getAction());
        return super.onTouchEvent(event);
    }
}

然后我们运行项目,点击button按钮,会得到如下的信息:

touch-button

点击button以外的地方,会得到如下的信息:

touch-layout

建议使用模拟器来运行点击事件。如果用真机的话,会触发大量的ACTION_MOVE事件。

事件分发的流程就出来了,那么为什么会是这样的呢?注意到事件都是从MainActivitydispatchTouchEvent()方法开始调用的,那我们就从这个方法开始着手看代码吧。

Activity 的事件分发

事件传递到Activity后,第一个触发的方法是dispatchTouchEvent(),我们看一看这个方法的源码:

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

好简单的代码,最喜欢看到这种“小清新”风格的代码了。

首先判断MotionEvent是不是ACTION_DOWN,如果是的话,执行onUserInteraction()方法,然后判断getWindow().superDispatchTouchEvent(ev)是否为true,如果为true,就不会执行onTouchEvent()方法,如果为false则执行onTouchEvent()方法。

onUserInteraction()

这个方法只有当ACTION_DOWN时才会触发, 那么这个方法是干嘛的?我们点进去看,会发现啥也没有。这个方法是空方法:

   /**
     * Called whenever a key, touch, or trackball event is dispatched to the
     * activity.  Implement this method if you wish to know that the user has
     * interacted with the device in some way while your activity is running.
     * This callback and {@link #onUserLeaveHint} are intended to help
     * activities manage status bar notifications intelligently; specifically,
     * for helping activities determine the proper time to cancel a notfication.
     *
     * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
     * be accompanied by calls to {@link #onUserInteraction}.  This
     * ensures that your activity will be told of relevant user activity such
     * as pulling down the notification pane and touching an item there.
     *
     * <p>Note that this callback will be invoked for the touch down action
     * that begins a touch gesture, but may not be invoked for the touch-moved
     * and touch-up actions that follow.
     *
     * @see #onUserLeaveHint()
     */
    public void onUserInteraction() {
    }

还好有注释,不然都不知道这个方法是用来干嘛的了。当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法。下拉statubar、旋转屏幕、锁屏不会触发此方法。所以它会用在屏保应用上,因为当你触屏机器 就会立马触发一个事件,而这个事件又不太明确是什么,正好屏保满足此需求。

getWindow().superDispatchTouchEvent(ev)

这个方法是干嘛的呢?我们点进superDispatchTouchEvent()看看:

   /**
     * Used by custom windows, such as Dialog, to pass the touch screen event
     * further down the view hierarchy. Application developers should
     * not need to implement or call this.
     *
     */
    public abstract boolean superDispatchTouchEvent(MotionEvent event);

意思大概是说,这个方法会在Dialog等界面中使用到,开发者不需要实现或者调用它。

纳尼?这样就把我们打发了?不带这样玩的啊…

我们注意到superDispatchTouchEvent()方法是getWindow()调用的,getWindow()方法返回的是一个Window对象。我们在Window类的说明中可以看到一下内容:

/**
 * Abstract base class for a top-level window look and behavior policy.  An
 * instance of this class should be used as the top-level view added to the
 * window manager. It provides standard UI policies such as a background, title
 * area, default key processing, etc.
 *
 * <p>The only existing implementation of this abstract class is
 * android.view.PhoneWindow, which you should instantiate when needing a
 * Window.
 */

相信大家的英语应该比我好,我就不翻译了,注意到这句话:The only existing implementation of this abstract class is android.view.PhoneWindow,这是说PhoneWindowWindow的唯一实现类。那么我们就可以在PhoneWindow类中看一下superDispatchTouchEvent()方法究竟干了什么。

PhoneWindow类中,我们可以看到如下代码:

@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
    return mDecor.superDispatchTouchEvent(event);
}

很简单,mDecor对象调用了superDispatchTouchEvent()方法。那么mDecor对象又是什么?

跳转到mDecor的声明,代码如下:

// This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;

发现原来mDecorDecorView的实例。等等,注释里面说,DecorView是视图的顶层view?

再跳转到DecorView类的定义处,发现这么一行代码:

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
    ......
}

现在我们清楚了,DecorView继承自FrameLayout,是我们编写所有的界面代码的父类。
然后我们看看mDecor.superDispatchTouchEvent()这个方法干了什么,也就是在DecorView类中,superDispatchTouchEvent()方法的内容:

public boolean superDispatchTouchEvent(MotionEvent event) {
    return super.dispatchTouchEvent(event);
}

嗯? 看不懂?注意,刚才我们已经知道了,DecorView是继承自FrameLayout,那么它的父类就应该是ViewGroup了,而super.dispatchTouchEvent(event)方法,其实就应该是ViewGroupdispatchTouchEvent()方法,不信?你可以点进去看看。

现在回到最开始的地方:在Activity 中:

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

其中getWindow().superDispatchTouchEvent(ev)的意义大概就清楚了,就是说,如果视图顶层的ViewGroup-DecorView类-的dispatchTouchEvnent()方法返回true的话,就不会执行onTouchEvent()方法了。

那么,问题来了,ViewGroup中的dispatchTouchEvent()方法什么时候返回true,什么时候返回false呢?

请看下回分解。

猜你喜欢

转载自blog.csdn.net/wl9739/article/details/51178311