这一篇文章主要讲解Android分发机制
为了能正确的理解,我们自定义一个ViewGroup,一个View
public class TestViewGroup extends LinearLayout {
public static final String TAG = "TestViewGroup";
public TestViewGroup(Context context) {
super(context, null);
}
public TestViewGroup(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TestViewGroup(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d(TAG, "dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent");
return super.onTouchEvent(event);
}
}
public class TestView extends TextView {
public static final String TAG = "TestView";
public TestView(Context context) {
this(context, null);
}
public TestView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d(TAG, "dispatchTouchEvent");
//getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent");
return super.onTouchEvent(event);
}
}
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.dy.touchevent.TestViewGroup
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=".MainActivity"
android:gravity="center">
<com.dy.touchevent.TestView
android:id="@+id/testView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TestView"/>
</com.dy.touchevent.TestViewGroup>
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
TestView mTestView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTestView = findViewById(R.id.testView);
//如果返回true,则不会调用onClick,onLongClick
mTestView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TestView.TAG, "onTouchListener");
return false;
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d(TAG, "dispatchTouchEvent");
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent");
return super.onTouchEvent(event);
}
}
我们分别重写Activity,ViewGroup,View的dispatchTouchEvent,onTouchEvent方法,加上Log,当我们在屏幕上点击TestView时,Log日志如下:
//action_down
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/MainActivity: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestViewGroup: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: onTouchListener
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: onTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestViewGroup: onTouchEvent
04-24 07:47:19.610 8168-8168/com.dy.touchevent D/MainActivity: onTouchEvent
//action_up
04-24 07:47:25.289 8168-8168/com.dy.touchevent D/MainActivity: dispatchTouchEvent
04-24 07:47:25.290 8168-8168/com.dy.touchevent D/MainActivity: onTouchEvent
从上到下传递
当屏幕上按下,产生一个ACTION_DOWN事件,这时会回调Activity的dispatchTouchEvent方法
Activity.java
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
onUserInteraction()方法是个空方法,不用管,它主要是用来检测分发事件用的,继续看Window
Window.java
public abstract boolean superDispatchTouchEvent(MotionEvent event);
Window是一个抽象类,它的唯一实现类是PhoneWindow
PhoneWindow.java
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
这个mDecor是一个DecorView,是布局文件的顶级View,它继承自FrameLayout
DecorView.java
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
它会调用父类,即ViewGroup的dispatchTouchEvent();
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
.....
if (actionMasked == MotionEvent.ACTION_DOWN) {
cancelAndClearTouchTargets(ev);
resetTouchState();
}
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
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;
}
.....
//父ViewGroup不拦截,传给子View
if (!canceled && !intercepted) {
.....
//找到正确的子View
for (int i = childrenCount - 1; i >= 0; i--) {
.....
//如果View在播放动画,或者点击事件的坐标x,y不在子View的区域内,则寻找下一个
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//找到了
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
.....
newTouchTarget = addTouchTarget(child, idBitsToAssign);
.....
}
}
}
}
dispatchTransformedTouchEvent里面作分发事件的操作,这个child不为空,所以分发给子view
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
return handled;
}
addTouchTarget()方法主要是把child赋给mFirstTouchTarget这个变量,之后会讲到。
接下来进入View的dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent event) {
.....
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;
}
}
.....
}
首先View会判断自身是否设置onTouchListener,如果设置了并且onTouch返回true,则直接返回true,消费了事件,则后续的onTouchEvent方法不会被调用,可见onTouchListener比onTouchEvent优先级高。接下来我们进入onTouchEvent看下
public boolean onTouchEvent(MotionEvent event) {
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
.....
performClick();
.....
}
}
}
它会判断view是否可点击,只要View的clickable和longclickable有一个为true,它就会消耗这个时间,并触发performClick()方法。
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
如果设置了OnClickListener,则调用它的onClick方法。到这里,ACTION_DOWN事件就从最顶级的Activity,到DecorView,到ViewGroup,最后到达子View,从上至下的过程,我们可以从Log日志看出来,也可正式onTouchListener比onTouchEvent优先级高
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/MainActivity: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestViewGroup: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: dispatchTouchEvent
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: onTouchListener
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestView: onTouchEvent
从下到上回传
接下来我们看看,子View没消费事件,则事件会从下往上回传给ViewGroup,即View的onTouchEvent返回false,则dispatchTouchEvent返回false,那么在ViewGroup的dispatchTransformedTouchEvent方法中handled为false
View.java
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = false;
.....
if (!result && onTouchEvent(event)) {
result = true;
}
.....
//返回false
return result;
}
ViewGroup.java
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
.....
handled = child.dispatchTouchEvent(event);
.....
return handled;
}
那么如果dispatchTransformedTouchEvent返回false,那么将不会执行newTouchTarget = addTouchTarget(child, idBitsToAssign);即mFirstTouchTarget为null,则会执行以下代码
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
child为空,则回执行super.dispatchTouchEvent(event);即View的dispatchTouchEvent(event),所以这时会执行ViewGroup里面的onTouchEvent,由于都返回false,所以导致ViewGroup的dispatchTouchEvent返回false,最后回到Activity中,所以回调Activity的onTouchEvent,从Log可以验证我们的设想。至此,时间从下往上传递也完成了。
//返回false,执行onTouchEvent
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
//Log
04-24 07:47:19.609 8168-8168/com.dy.touchevent D/TestViewGroup: onTouchEvent
04-24 07:47:19.610 8168-8168/com.dy.touchevent D/MainActivity: onTouchEvent
ACTION_UP
04-24 07:47:25.289 8168-8168/com.dy.touchevent D/MainActivity: dispatchTouchEvent
04-24 07:47:25.290 8168-8168/com.dy.touchevent D/MainActivity: onTouchEvent
为什么ACTION_UP事件只回调了MainActivity的方法呢,ViewGroup,View的相关方法为什么为回调呢?其实回调了ViewGroup的相关方法,只不过之前ACTION_DOWN方法子View没消费,那么之后的一系列事件都不会传给子View了,除非在遇到ACTION_DOWN,因为一个完成整的屏幕触摸操作是由一个ACTION_DOWN开始,中间有或没有ACTION_MOVE,以ACTION_UP结束。
action.png
其实可以断点进去查看事件的分发流程,断点查看是学习Android Framework源码的最好途径。 由之前ACTION_DOWN事件往上传递,得知mFirstTouchTarget为null,我们继续进入ViewGroup的dispatchTouchEvent
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
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;
}
可以看到,由于是ACTION_UP事件并且mFirstTouchTarget为null,则直接令intercepted为true,事件不再往下传递,由自身拦截。
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
}
后面的流程跟ACTION_DOWN事件往上传递是一样的,直接回调ViewGroup的onTouchEvent()方法,由于都返回false,所以最后会回调Activity的onTouchEvent方法。
这里还有个标志位FLAG_DISALLOW_INTERCEPT,这个是干什么用的呢,这个是子View干预父View的拦截操作,即子View通知父ViewGroup不要拦截它的事件。当子View设置FLAG_DISALLOW_INTERCEPT为true时,则disallowIntercept 为true,直接就令intercepted为false了,这样父ViewGroup就不会拦截事件,不会调用onInterceptTouchEvent,可见,onInterceptTouchEvent不是每次都会被调用的。
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
//子view调用
getParent().requestDisallowInterceptTouchEvent(true);
那是不是之后的所有事件都不拦截了呢,错了,当新的ACTION_DOWN事件来到是,会重置FLAG_DISALLOW_INTERCEPT为false
/**
* Resets all touch state in preparation for a new cycle.
*/
private void resetTouchState() {
clearTouchTargets();
resetCancelNextUpFlag(this);
//重置
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
mNestedScrollAxes = SCROLL_AXIS_NONE;
}
这也比较好理解,因为完整的事件序列以ACTION_DOWN开头。
网友评论