一、思维导图
二、View的事件分发机制
2.1 源码了解Activity
我们知道Activity是应用“页面”,用户的一系列手势操作都是在与Activity打交道,当用户点击屏幕会产生一个点击事件(MotionEvent),而该事件最先传递给的就是Activiity。所以学习View的事件分发机制避不开去了解Activity。在我们创建一个Activity的时候,在它的onCreate()方法中会有setContentView()方法,我们就从这里“动手”开始分析View的事件分发。
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);//①
initWindowDecorActionBar();
}
①中的getWindow()会返回一个Window对象,其实查看源码我们会发现这个window对象就是PhoneWindow。在PhoneWindow.java类中我们查看setContentView()方法:
图1
注意其中红色圈中的installDecor()方法。点进去查看关键的代码截图如下:
图2
我们先查看第一个红色框内的generateDecor()方法,点进去继续看会发现一个对象——DecorView:
图3
该DecorView就是Activity中的根View,DecorView继承与FrameLayout。在图2中,我们的第二个红色方框中的方法源码中关键代码截图是:
很明显这是一个xml代码。打开如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
style="?android:attr/windowTitleBackgroundStyle">
<TextView android:id="@android:id/title"
style="?android:attr/windowTitleStyle"
android:background="@null"
android:fadingEdge="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
<ViewStub/>显示ActionBar。第一个<FrameLayout/>用来显示title,第二个<FrameLayout/>用来显示内容content。总结一个Activity包含了一个Window对象,该抽象对象具体由PhoneWindow来实现。DecorView是PhoneWindow的根View,将屏幕分为两个区域:TitleView和ContentView。
2.2 MotionEvent事件点击类
Android中点击事件被封装成类MotionEvent,对象产生后系统会将MotionEvent传递给View的不同层级,而MotionEvent在View的不同层级间的传递过程就是点击事件分发。在正式学习事件分发原理前,介绍三个重要的方法:
- dispatchTouchEvent(MotionEvent event):分发事件
- onInterceptTouchEvent(MotionEvent event):拦截事件,在dispatchTouchEvent()中调用,View没有提供该方法,它在ViewGroup中提供。
- onTouchEvent(MotionEvent event):处理点击事件,在dispatchTouchEvent()方法中调用。
2.2.1 基本原理
事件分发的原理我们可以这样理解记忆:老总吩咐一项事情给你的主管,你的主管又把事情分配到你的手头负责。这个过程其实就是事件的传递过程:
老总-->主管-->员工(你自己)
同理,你把任务完成需要汇报给主管,主管再汇报给老总。事件的处理过程:
员工-->主管-->老总
事件如此传递是完美的,但是现实不是完美的。有时候你遇到的任务超出能力范围,这个时候你会告诉主管“我规定时间无法完成”,主管为了不拖进度,只好自己把事情扛了过来做,然后做完汇报给老总。
主管-->老总
更甚者,主管也无能为力,只好请老总亲自出马:
老总
具体到代码就是:
事件传递返回值:true——表示拦截该事件,不再继续向下传递;false——表示不拦截,继续向下传递。
而事件的处理返回值:true——表示该事件已经处理了,你不用处理了;false——表示我无能为力,你来帮我处理好了。