一箫一剑平生意,负尽狂名十五年。这篇文章主要讲述理解并测试什么是Android事件分发相关的知识,希望能为你提供帮助。
一、什么是事件分发所谓事件分发,就是将一次完整的点击所包含的点击事件传递到某个具体的View或ViewGroup,让该View或该ViewGroup处理它(消费它)。分发是从上往下(父到子)依次传递的,其中可能经过的对象有最上层Activity,中间层ViewGroup,最下层View。
二、Activity的层次结构源码查找:
1.自己的Activity的setContentView()
方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_distribution);
}
2.跳转到Activity.java的
setContentView()
方法,可以看到,调用了getWindow()
的方法public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
3.Activity.java的mWindow来自
PhoneWindow
mWindow = new PhoneWindow(this, window, activityConfigCallback);
4.PhoneWindow.java--> setContentView()--> ?installDecor(),在PhoneWindow中调用了
installDecor()
方法@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
//继续执行
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
..................
5.PhoneWindow.java--> setContentView()--> ?installDecor()--> ?generateLayout(mDecor),在?installDecor()中又继续执行了
generateLayout(mDecor)
方法。 mContentParent = generateLayout(mDecor);
6.PhoneWindow.java--> generateLayout()
ViewGroup generateLayout(DecorView decor)
7.PhoneWindow.java--> generateLayout()--> ?int layoutResource,
layoutResource
根据不同情况,返回不同的资源文件,也就是布局文件。int layoutResource;
8.PhoneWindow.java--> generateLayout()--> R.layout.screen_title; 拿出一个常用的布局文件,
screen_title.xml
layoutResource = R.layout.screen_title;
9.screen_title.xml的代码,
ViewStub
是用来显示ActionBar
的,另外两个FrameLayout,一个显示TitleView
,一个显示ContentView,平时写的内容,正是ContentView
。<
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>
如以下结构图:
文章图片
三、事件分发涉及到的主要方法涉及到的方法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分发事件
return super.dispatchTouchEvent(ev);
}@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//拦截事件
return super.onInterceptTouchEvent(ev);
}@Override
public boolean onTouchEvent(MotionEvent event) {
//消费事件
return super.onTouchEvent(event);
}
Activity涉及到的方法:dispatchTouchEvent()、onTouchEvent()
ViewGroup涉及到的方法:dispatchTouchEvent()、onInterceptTouchEvent()
View涉及到的方法:dispatchTouchEvent()、onTouchEvent()
四、事件分发流程 1.Activity把事件分发到ViewGroup (1)事件传递
每一次事件分发,都是从dispatchTouchEvent()开始的。
1)查看Activity的源码,调用了
getWindow().superDispatchTouchEvent(ev)
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
2)在Activity.java中可以看到,所以
getWindow().superDispatchTouchEvent(ev)
实际上是调用了PhoneWindow.java中的superDispatchTouchEvent(ev)
方法。 public Window getWindow() {
return mWindow;
} mWindow = new PhoneWindow(this, window, activityConfigCallback);
//mWindow的定义
3)然后再看PhoneWindow.java中的
superDispatchTouchEvent(ev)
方法,是调用DecorView.java的mDecor.superDispatchTouchEvent(event)
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
4)而DecorView是继承FrameLayout,再继承ViewGroup的
private DecorView mDecor;
//实例对象
class DecorView extends FrameLayout;
//继承FrameLayout
FrameLayout extends ViewGroup;
//继承ViewGroup
5)从上面四步来分析,Avtivity的
getWindow().superDispatchTouchEvent()
方法最后调用的是ViewGroup的dispatchTouchEvent()
方法,从而实现了事件从Activity的dispatchTouchEvent()
向下传递到ViewGroup的dispatchTouchEvent()
方法。(2)总结
6)返回值分析。
- 如果Avtivity的
getWindow().superDispatchTouchEvent()
返回true,则Avtivity的dispatchTouchEvent(),也会返回true,表示点击事件顺利分发给ViewGroup,由ViewGroup继续进行下一层的分发,Avtivity的分发任务结束。 - 如果返回false,表示此次点击事件由Avtivity层消费,会执行Avtivity的
onTouchEvent()
,无论onTouchEvent()
这个方法返回的是true或者false,本次的事件分发都结束了。
文章图片
2.ViewGroup把事件分发到ViewGroup或View (1)事件拦截
ViewGroup.java中的部分代码
ViewGroup-->
dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action);
// restore action in case it was changed
} else {
intercepted = false;
}
}
方法中使用了
onInterceptTouchEvent(ev)
方法- 如果返回true,则表示ViewGroup拦截此次事件。
- 如果返回false,则表示ViewGroup不拦截,事件继续往下分发。
onInterceptTouchEvent(ev)
默认返回不拦截,可以在ViewGroup中重写改方法来拦截事件。- 不拦截事件,则会调用ViewGroup的onTouchEvent()来处理点击事件,把事件消费掉。
这个源码中,使用到了intercepted这个变量,主要作用是来遍历子ViewGroup和View,
- 当intercepted为false的时候,遍历子ViewGroup和子View,因为这个事件没有被消费掉,继续分发到子ViewGroup和子View。
- 当intercepted为true的时候,该事件已经被消费,不会继续往下分发,也不会遍历子ViewGroup和子View,也不会执行if语句里面的方法。
- 进入if语句中判断点击事件的触摸范围(焦点)是否属于某个子ViewGroup或者子View。
- 如果触摸范围属于子View,则调用子View的dispatchTouchEvent()方法。
- 如果触摸范围属于子ViewGroup,则继续遍历下一层的ViewGroup或者View。
- 遍历到最下层的View,还是找不到消费此处事件的View,则依次回调上一层的ViewGroup的onTouchEvent()方法,直到回调到Activity的onTouchEvent()方法。
// Check for interception.
final boolean intercepted;
if (!canceled &
&
!intercepted) {// If the event is targeting accessibility focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
(3)流程图
文章图片
3.View的事件分发 (1)分析
View的dispatchTouchEvent()的源码
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don‘t have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags &
ENABLED_MASK) == ENABLED &
&
handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null &
&
li.mOnTouchListener != null
&
&
(mViewFlags &
ENABLED_MASK) == ENABLED
&
&
li.mOnTouchListener.onTouch(this, event)) {
result = true;
}if (!result &
&
onTouchEvent(event)) {
result = true;
}
}if (!result &
&
mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn‘t want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN &
&
!result)) {
stopNestedScroll();
}return result;
}
- 在View的dispatchTouchEvent()方法中首先会调用
onTouch()
方法,如果onTouch()方法能够消费该事件,就会直接返回True,从而直接结束View的dispatchTouchEvent()方法,不再执行onTouchEvent()方法; - 如果onTouch()方法不能消费该事件,就会返回False,从而继续执行
onTouchEvent``()
方法。 - 如果onTouchEvent()能够消费该事件,就会返回True从而直接结束dispatchTouchEvent()方法。
- 如果onTouchEvent()方法也不能消费该事件,就会返回默认的False从而回调到上一层
ViewGroup
的onTouchEvent()方法,直到回调到Activity的onTouchEvent``()
方法。
文章图片
五、具体例子 (0)测试代码共有三种类型和四个测试代码
Activity:EventDistributionActivity
ViewGroup:EventDistributionLinearLayout1、EventDistributionLinearLayout2
View:EventDistributionButton
分别代码:
EventDistributionActivity.java
public class EventDistributionActivity extends BaseActivity {
Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_distribution);
mBtn = findViewById(R.id.btn);
OnClick();
}public void OnClick() {
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("
showLog"
, "
按钮被点击!"
);
}
});
mBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean dis = false;
Log.v("
showLog"
, "
Button.Touch()="
+ dis);
return dis;
}
});
}@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分发事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("
showLog"
, "
Activity.dispatchTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onTouchEvent(MotionEvent event) {
//处理事件
boolean dis = super.onTouchEvent(event);
Log.v("
showLog"
, "
Activity.onTouchEvent()="
+ dis);
return dis;
}}
EventDistributionLinearLayout1.java
public class EventDistributionLinearLayout1 extends LinearLayout {
public EventDistributionLinearLayout1(Context context, AttributeSet attrs) {
super(context, attrs);
}@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分发事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("
showLog"
, "
LinearLayout1.dispatchTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//拦截事件
boolean dis = super.onInterceptTouchEvent(ev);
Log.v("
showLog"
, "
LinearLayout1.onInterceptTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onTouchEvent(MotionEvent event) {
//消费事件
boolean dis = super.onTouchEvent(event);
Log.v("
showLog"
, "
LinearLayout1.onTouchEvent()="
+ dis);
return dis;
}
}
EventDistributionLinearLayout2.java
public class EventDistributionLinearLayout2 extends LinearLayout {
public EventDistributionLinearLayout2(Context context, AttributeSet attrs) {
super(context, attrs);
}@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//分发事件
boolean dis = super.dispatchTouchEvent(ev);
Log.v("
showLog"
, "
LinearLayout2.dispatchTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//拦截事件
boolean dis = super.onInterceptTouchEvent(ev);
dis = true;
Log.v("
showLog"
, "
LinearLayout2.onInterceptTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onTouchEvent(MotionEvent event) {
//消费事件
boolean dis = super.onTouchEvent(event);
Log.v("
showLog"
, "
LinearLayout2.onTouchEvent()="
+ dis);
return dis;
}
}
EventDistributionButton.java
public class EventDistributionButton extends Button {
public EventDistributionButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
//分发事件
boolean dis = super.dispatchTouchEvent(event);
Log.v("
showLog"
, "
Button.dispatchTouchEvent()="
+ dis);
return dis;
}@Override
public boolean onTouchEvent(MotionEvent event) {
//消费事件
boolean dis = super.onTouchEvent(event);
Log.v("
showLog"
, "
Button.onTouchEvent()="
+ dis);
return dis;
}@Override
public boolean performClick() {
boolean dis = super.performClick();
Log.v("
showLog"
, "
Button.performClick()="
+dis);
return dis;
}}
activity_event_distribution.xml
<
?xml version="
1.0"
encoding="
utf-8"
?>
<
com.lanjiabin.systemtest.event.EventDistributionLinearLayout1 xmlns:android="
http://schemas.android.com/apk/res/android"
xmlns:app="
http://schemas.android.com/apk/res-auto"
xmlns:tools="
http://schemas.android.com/tools"
android:layout_width="
match_parent"
android:layout_height="
match_parent"
android:orientation="
vertical"
tools:context="
.event.EventDistributionActivity"
>
<
com.lanjiabin.systemtest.event.EventDistributionLinearLayout2
android:layout_width="
match_parent"
android:layout_height="
match_parent"
android:orientation="
vertical"
>
<
com.lanjiabin.systemtest.event.EventDistributionButton
android:background="
@drawable/button_color_circle_shape1"
android:id="
@+id/btn"
android:layout_width="
wrap_content"
android:layout_height="
wrap_content"
android:layout_gravity="
center"
android:layout_marginTop="
300dp"
android:text="
点击"
/>
<
/com.lanjiabin.systemtest.event.EventDistributionLinearLayout2>
<
/com.lanjiabin.systemtest.event.EventDistributionLinearLayout1>
效果图:一个LinearLayout1包含LinearLayout2再包含一个Button
界面只有一个按钮
文章图片
(1)测试1测试用例:按钮消费事件,和空白处不消费事件
按住按钮不松开,事件被Button的onTouchEvent()消费
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
按住空白处不松开,没有事件被消费
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
LinearLayout2.onTouchEvent()=false
LinearLayout2.dispatchTouchEvent()=false
LinearLayout1.onTouchEvent()=false
LinearLayout1.dispatchTouchEvent()=false
Activity.onTouchEvent()=false
Activity.dispatchTouchEvent()=false
(2)测试2测试用例:在LinearLayout2处截断
修改代码:EventDistributionLinearLayout2.java
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//拦截事件
boolean dis = super.onInterceptTouchEvent(ev);
dis = true;
Log.v("
showLog"
, "
LinearLayout2.onInterceptTouchEvent()="
+ dis);
return dis;
}
按住按钮不松开:事件截断生效,将不会继续遍历下层的ViewGroup或者View,所以日志中看不到Button的日志打印。
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=true//截断生效
LinearLayout2.onTouchEvent()=false
LinearLayout2.dispatchTouchEvent()=false
LinearLayout1.onTouchEvent()=false
LinearLayout1.dispatchTouchEvent()=false
Activity.onTouchEvent()=false
Activity.dispatchTouchEvent()=false
(3)测试3测试用例:在View中onTouch()中返回true
也就是在Button中设置onTouch()返回true,则不会产生点击事件,完整的点击事件是被按下和松开的,所以上面没有点击按钮的监听事件的打印日志。
首先,看看完整的点击事件日志,去掉先前测试的改变的代码。
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true//触摸按下事件被消费
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true//触摸按下的事件处理结束
LinearLayout1.onInterceptTouchEvent()=false//开始触摸i抬起的事件
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=false
Button.onTouchEvent()=true //触摸抬起的事件被消费
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
按钮被点击!//onClick
Button.performClick()=true
开始测试用例:
修改代码:
EventDistributionActivity.java,将
boolean dis = false;
修改为boolean dis = true;
mBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
boolean dis = true;
Log.v("
showLog"
, "
Button.Touch()="
+ dis);
return dis;
}
});
按下和松开按钮:可以看到,事件被Button.Touch()消费了,因为在Touch()返回了true,事件没有继续传递下去,所以onClick事件没有被触发,没有生效。
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=true//触摸事件被消费
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true //触摸按下事件处理完毕
LinearLayout1.onInterceptTouchEvent()=false
LinearLayout2.onInterceptTouchEvent()=false
Button.Touch()=true
Button.dispatchTouchEvent()=true
LinearLayout2.dispatchTouchEvent()=true
LinearLayout1.dispatchTouchEvent()=true
Activity.dispatchTouchEvent()=true
【理解并测试什么是Android事件分发】编程中我们会遇到多少挫折?表放弃,沙漠尽头必是绿洲。
推荐阅读
- [Blazor] - 关于 "HTTP Error 500.38 - ANCM Application DLL Not Found" 的调整及相关资料
- multipart/form-data和application/x-www-form-urlencoded的区别
- Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting
- NetCore+Dapper WebApi架构搭建(仓储的依赖注入)
- Android应用的persistent属性
- 安卓测试
- RichFaces rich(fileUpload组件用法)
- 安卓逆向14.Nexus 5 线刷官方镜像root开始系统调试
- 关于APP内嵌H5后退按钮问题