一、简介
在android中,重要性方面除了四大组件基本上就是View了,View甚至比Receiver和Provider更重要。在开发过程中,我们经常遇到需要自定义View来实现特殊功能、View之间的事件冲突(尤其是滑动冲突)等,要解决这些问题,我们都必须要对View/ViewGroup的事件有足够充分的理解。本篇文字大致内容如下图所示:
二、View基础
View是Android中所有控件的基类,无论是TextView、Button或是LinearLayout、RelativeLayout它们都是继承自View,处理View还有一个重要的控件组--ViewGroup,它其实也是继承自View,ViewGroup内部可以包含其他多个View。
2.1)View中控件关系
下图为截取网上的一个控件之间继承关系图,红色部分为常用控件。
2.2)View中有关位置关系方法
在理解有关Android View事件之前,对View的位置参数的了解是不可缺少的,View的位置主要由四个顶点来决定即:top、left、right、buttom,分别可以用如下四个函数获取对应值:
view.getLeft());
view.getTop());
view.getRight());
view.getBottom());
那他们具体表示什么含义,如下图所示:
他们获取的值是针对父布局而言的,因此是一种相对值。
那么我们如何获取控件的绝对坐标呢?
int[] location1 = new int[2] ;
view.getLocationInWindow(location1); //获取在当前窗口内的绝对坐标
int[] location2 = new int[2] ;
view.getLocationOnScreen(location2);//获取在整个屏幕内的绝对坐标
窗口是指window,屏幕就是整个屏幕了,看源码可一发现,屏幕绝对坐标=窗口绝对坐标+windowLeft,
也就是window的偏移量。
从Android3.0开始,View增加了几个额外的参数:x、y、translationX、translationY,其中x、y表示View左上角的坐标,而translationX、translationY表示View左上角相对父容器的偏移量,默认值一般是0,只有当View发送移动的时候才会出现偏移量。具体函数如下:
view.getX())
view.getY())
view.getTranslationX())
view.getTranslationY())
那么问题来了,这里的x、y和上面的left、top有啥区别呢?
如果是首次加载布局,他们的值确实相等,如果当View发生移动的时候,top、left的值仍然是不会改变的,但是x、y是会发生改变的。下面我们以一个实例为证。
xml布局文件
<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"
android:orientation="vertical"
android:background="#ffffff">
<LinearLayout
android:id="@+id/layout_parent"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="#eeeeee">
<Button
android:id="@+id/btn_child"
android:layout_width="100dp"
android:layout_height="50dp"
android:background="#cccccc"
android:layout_margin="10dp"/>
</LinearLayout>
</LinearLayout>
activity代码
public void initView(){
layoutParent = (LinearLayout) findViewById(R.id.layout_parent);
btnChild = (Button) findViewById(R.id.btn_child);
btnChild.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
printLog();
translateBtnChild();
}
});
}
private void printLog(){
Log.i("DemoActivity", "btnChild--getX: "+btnChild.getX());
Log.i("DemoActivity", "btnChild--getY: "+btnChild.getY());
Log.i("DemoActivity", "btnChild--getLeft: "+btnChild.getLeft());
Log.i("DemoActivity", "btnChild--getTop: "+btnChild.getTop());
Log.i("DemoActivity", "btnChild--getTranslationX: "+btnChild.getTranslationX());
Log.i("DemoActivity", "btnChild--getTranslationY: "+btnChild.getTranslationY());
}
// 动画,让View沿着X轴移动50px
private void translateBtnChild() {
ObjectAnimator animator = ObjectAnimator.ofFloat(btnChild,"translationX",50.0f);
animator.setDuration(100);
animator.start();
}
点击两次,log输出如下:
// 第一次点击
DemoActivity: btnChild--getX: 30.0
DemoActivity: btnChild--getY: 30.0
DemoActivity: btnChild--getLeft: 30
DemoActivity: btnChild--getTop: 30
DemoActivity: btnChild--getTranslationX: 0.0
DemoActivity: btnChild--getTranslationY: 0.0
// 第二次点击
DemoActivity: btnChild--getX: 80.0
DemoActivity: btnChild--getY: 30.0
DemoActivity: btnChild--getLeft: 30
DemoActivity: btnChild--getTop: 30
DemoActivity: btnChild--getTranslationX: 50.0
DemoActivity: btnChild--getTranslationY: 0.0
事实证明,top、left的值是不会改变的,但是x、y是会发生改变的。且x=left+translationX,y=top+translationY。
三、事件机制
在对View有一定理解后,接下来将进入本篇核心部分----事件机制。
以上面代码为例,我们通常给一个控件(例如Button)增加点击事件,直接setOnClickListener即可,那么有没有去思考,当发生手指/鼠标点击时,事件是如何进行传递的呢?
3.1) 事件分发三剑客
当发生点击事件时,点击事件并不是发生在当前的点击View上,事件是从window开始,逐级向下传递,直到当前点击的View,这个传递的事件对象即为MotionEvent。MotionEvent在传递/分发过程中,由三个很重要的方法来共同完成,这三个方法分别为:
public boolean onInterceptTouchEvent(MotionEvent ev)
public boolean dispatchTouchEvent(MotionEvent event)
public boolean onTouchEvent(MotionEvent event)
这三个函数,默认返回值都为false。
我们看看如下demo,接下来的例子都是基于此demo。
- MyViewGroupA
public class MyViewGroupA extends LinearLayout{
public MyViewGroupA(Context context) {
super(context);
}
public MyViewGroupA(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyViewGroupA(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean result = super.dispatchTouchEvent(ev);
Log.i("MyViewGroupA","dispatchTouchEvent-->result: "+result);
return result;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean result = super.onInterceptTouchEvent(ev);
Log.i("MyViewGroupA","onInterceptTouchEvent-->result: "+result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = super.onTouchEvent(event);
Log.i("MyViewGroupA","onTouchEvent-->result: "+result);
if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.i("MyViewGroupA","onTouchEvent-->MotionEvent.ACTION_DOWN");
}else if(event.getAction() == MotionEvent.ACTION_UP){
Log.i("MyViewGroupA","onTouchEvent-->MotionEvent.ACTION_UP");
}else if(event.getAction() == MotionEvent.ACTION_MOVE){
Log.i("MyViewGroupA","onTouchEvent-->MotionEvent.ACTION_MOVE");
}
return result;
}
}
- MyViewGroupB
内容同MyViewGroupA,仅仅Log日志的Key不同而已。
- MyView
public class MyView extends android.support.v7.widget.AppCompatTextView{
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = super.dispatchTouchEvent(event);
Log.i("MyView","dispatchTouchEvent-->result: "+result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = super.onTouchEvent(event);
Log.i("MyView","onTouchEvent-->result: "+result);
if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.i("MyView","onTouchEvent-->MotionEvent.ACTION_DOWN");
}else if(event.getAction() == MotionEvent.ACTION_UP){
Log.i("MyView","onTouchEvent-->MotionEvent.ACTION_UP");
}else if(event.getAction() == MotionEvent.ACTION_MOVE){
Log.i("MyView","onTouchEvent-->MotionEvent.ACTION_MOVE");
}
return result;
}
}
最后在activity中xml布局大致如下:
<com.example.MyViewGroupA
android:layout_width="200dp"
android:layout_height="100dp"
android:background="#eeeeee"
android:gravity="center">
<com.example.MyViewGroupB
android:layout_width="150dp"
android:layout_height="70dp"
android:background="#988945"
android:gravity="center">
<com.example.MyView
android:id="@+id/myview"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="事件分发"
android:background="#FF4081"/>
</com.example.MyViewGroupB>
</com.example.MyViewGroupA>
最终的界面显示如下:
当我们点击MyView,可以看到log输出如下:
MyViewGroupA: onInterceptTouchEvent-->result: false
MyViewGroupB: onInterceptTouchEvent-->result: false
MyView: onTouchEvent-->result: false
MyView: onTouchEvent-->MotionEvent.ACTION_DOWN
MyView: dispatchTouchEvent-->result: false
MyViewGroupB: onTouchEvent-->result: false
MyViewGroupB: onTouchEvent-->MotionEvent.ACTION_DOWN
MyViewGroupB: dispatchTouchEvent-->result: false
MyViewGroupA: onTouchEvent-->result: false
MyViewGroupA: onTouchEvent-->MotionEvent.ACTION_DOWN
MyViewGroupA: dispatchTouchEvent-->result: false
从log输出可以得出如下结论:
- 函数的返回值默认都为false;
- onInterceptTouchEvent方法是在事件传递的时候执行,由上往下一层一层传递(并且只有ViewGroup才有此方法);
- onTouchEvent和dispatchTouchEvent是在事件处理的时候执行,由下往上一层一层处理。
下面我们详细来说说这三个函数。
3.1.1)onInterceptTouchEvent
通过函数名大概能猜测到即为拦截事件函数,该方法只有继承ViewGroup类才有,同一个事件序列,只会调用一次 ,返回的结果表示是否拦截当前事件 true:表示拦截如果拦截,则只会执行 当前view的 onTouchEvent和dispatchTouchEvent方法;false:表示不拦截,则事件继续向下传递。
onInterceptTouchEvent设置为返回true,真是如上所说吗?
我们将MyViewGroupB中的onInterceptTouchEvent设置返回为true,如下所示:
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
super.onInterceptTouchEvent(ev);
boolean result = true
Log.i("MyViewGroupB","onInterceptTouchEvent-->result: "+result);
return result ;
}
点击log输出如下:
MyViewGroupA: onInterceptTouchEvent-->result: false
MyViewGroupB: onInterceptTouchEvent-->result: true
MyViewGroupB: onTouchEvent-->result: false
MyViewGroupB: onTouchEvent-->MotionEvent.ACTION_DOWN
MyViewGroupB: dispatchTouchEvent-->result: false
MyViewGroupA: onTouchEvent-->result: false
MyViewGroupA: onTouchEvent-->MotionEvent.ACTION_DOWN
MyViewGroupA: dispatchTouchEvent-->result: false
从log输出可以得出如下结论:
- onInterceptTouchEvent 返回为true,表示对事件进行拦截,也就是说事件不会再分发到下一个View;
- onInterceptTouchEvent 返回为true,表示事件传递到当前View则截止了,接下来开始事件处理流程,也就是从当前View出发往上传递直到某个View处理当前触发的事件。
看到这里,不知大家有没有发现一个问题,当我们手指/鼠标点击到按钮的时候,讲道理至少是有ACTION_DOWN和ACTION_UP两个Event的,通过log输出,为什么没有看到UP的log输出呢?
在此先留给读者思考,下文将会详细讲述。
3.1.2)onTouchEvent
事件处理/消费函数,当返回为true,表示对之间进行处理也就是对该事件进行接收,事件由于已经处理所以不会对该事件再次上传到上一级View中使其执行onTouchEvent函数。
我们看看demo如下,将MyViewGroupB的onTouchEvent函数返回true:
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
boolean result = true;
Log.i("MyViewGroupB","onTouchEvent-->result: "+result);
if(event.getAction() == MotionEvent.ACTION_DOWN){
Log.i("MyViewGroupB","onTouchEvent-->MotionEvent.ACTION_DOWN");
}else if(event.getAction() == MotionEvent.ACTION_UP){
Log.i("MyViewGroupB","onTouchEvent-->MotionEvent.ACTION_UP");
}else if(event.getAction() == MotionEvent.ACTION_MOVE){
Log.i("MyViewGroupB","onTouchEvent-->MotionEvent.ACTION_MOVE");
}
return true;
}
log日志输出如下:
I/MyViewGroupA: onInterceptTouchEvent-->result: false
I/MyViewGroupB: onInterceptTouchEvent-->result: false
I/MyView: onTouchEvent-->result: false
I/MyView: onTouchEvent-->MotionEvent.ACTION_DOWN
I/MyView: dispatchTouchEvent-->result: false
I/MyViewGroupB: onTouchEvent-->result: true
I/MyViewGroupB: onTouchEvent-->MotionEvent.ACTION_DOWN
I/MyViewGroupB: dispatchTouchEvent-->result: true
I/MyViewGroupA: dispatchTouchEvent-->result: true
I/MyViewGroupA: onInterceptTouchEvent-->result: false
I/MyViewGroupB: onTouchEvent-->result: true
I/MyViewGroupB: onTouchEvent-->MotionEvent.ACTION_UP
I/MyViewGroupB: dispatchTouchEvent-->result: true
I/MyViewGroupA: dispatchTouchEvent-->result: true
从log输出可以得出如下结论:
- onTouchEvent函数的返回值影响这当前View及上层View的dispatchTouchEvent的返回值;
- 当前View的onTouchEvent返回为true,表示消耗了当前事件,则上层的View是不会执行onTouchEvent方法的,但是会执行dispatchTouchEvent方法。
细心的读者会发现,MyViewGroupA会执行两次onInterceptTouchEvent函数,MyViewGroupA执行了ACTION_UP事件。
这是为什么呢?
在这里来解答一下上面留下的疑问。
在Android系统中,一个单独的事件基本上是没什么作用的,只有一个事件序列,才有意义。一个事件序列正常情况下,定义为 DOWN、MOVE(0或者多个)、UP/CANCEL。事件序列以DOWN事件开始,中间会有0或者多个MOVE事件,最后以UP事件或者CANCEL事件结束。
DOWN事件作为序列的开始,有一个很重要的职责,就是寻找事件序列的接受者,怎么理解呢?framework 在DOWN事件的传递过程中,需要根据View事件处理方法(onTouchEvent)的返回值来确定事件序列的接受者。如果一个View的onTouchEvent事件,在处理DOWN事件的时候返回true,说明它愿意接受并处理该事件序列。
因此在该示例中,鼠标点击的DOWN和UP是为一个事件序列,由于MyViewGroupB接受并处理该事件序列,因此UP事件还需通过MyViewGroupA传递到MyViewGroupB,MyViewGroupB然后在处理UP事件。同时需要注意的是当整个事件传递过程中,当发现没有View对DOWN进行接受处理时,那么该事件序列的其他事件将不再进行传递,这也正说明了开始的log输出,只看到DOWN而没有看到UP。
3.1.3)dispatchTouchEvent
看名称顾名思义为事件分发函数,默认情况下,该函数的返回值受当前 View的onTouchEvent和下级View的onInterceptTouchEvent方法影响。
其实 ,上层dispatchTouchEvent返回值是受下一层dispatchTouchEvent返回值影响的,并不是下层的onTouchEvent返回值;
其实,当前view能否对同一事件序列的其他事件进行处理例如移动或离开,也是受到dispatchTouchEvent返回值影响的,并不是onTouchEvent的返回值。
此处就不在利用demo来说明,读者可以自行测试。
3.2) 事件传递机制原理
当Android设备的屏幕,接收到触摸的动作时,屏幕驱动把压力信号(包括压力大小,压力位置等)传递给系统底层,然后操作系统经过一系列的处理,然后把触摸事件一层一层的向上传递,最终事件会被准确的传递到产生事件的对象上,系统会遍历每一个View对象,然后计算触摸点在哪一个View中。这里首先概要的简述了事件的产生到最后的传递处理。
当我们在一个Activity中的某个View发生点击事件时,事件最先传递给当前的Activity,由Activity的dispatchTouchEvent来进行事件派发,之后交给Window来完成。
看到这里大家可能有疑问了,通过3.1的log输出,不是函数的执行顺序是onInterceptTouchEvent-->onTouchEvent-->dispatchTouchEvent 这样的吗,怎么会最先执行的是dispatchTouchEvent方法呢?
要解答这个问题,必须的看看ViewGoup 中 dispatchTouchEvent中的代码了。具体如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
......
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
......
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
// 此处执行了 onInterceptTouchEvent
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
......
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity 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;
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
......
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
......
// dispatchTransformedTouchEvent 中调用了super.dispatchTouchEvent
// 也就是View中的dispatchTouchEvent,查看View中的dispatchTouchEvent方法,发现有调用 onTouchEvent方法
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
.......
return handled;
}
dispatchTouchEvent十分重要,onInterceptTouchEvent和onTouchEvent都是在该方法中执行的,同时通过代码还能看到事件是
如何分发给下一个View。
我们继续回到Activity中的dispatchTouchEvent方法,可以看到代码如下:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
通过代码可以发现首先把事件交给Window进行分发,如果返回true则整个事件结束,否则将会执行activity的onTouchEvent方法。
接下来看看Window是如何将事件传递给ViewGroup的,我们知道Window是一个抽象类,它的实现类为PhoneWindow。
// public class DecorView extends FrameLayout
private DecorView mDecor;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
// DecorView 中
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
可以看到,PhoneWindow将事件直接传递给了DecorView,查看DecorView代码,它继承FrameLayout,DecorView中同样,将事件传递给父类,最终到ViewGrop的dispatchTouchEvent方法中,这也是Activity中的根View(即定级View)了。在ViewGroup的dispatchTouchEvent方法中,可以清楚看到事件是如何进行分发的。
首先获取事件的坐标点,在dispatchTouchEvent中从根View向子View遍历,判断点坐标在该子View中,然后判断该子View是否对事件进行处理,处理则事件不在进行向下传递。
参考文献
《Android开发艺术探索》
https://www.jianshu.com/p/38015afcdb58
https://www.cnblogs.com/xyhuangjinfu/p/5433688.html