您的位置:首页 > 移动开发 > Android开发

Android事件分发机制源码畅游解析(ViewGroup篇)

2017-04-23 16:33 477 查看
CSDN怎么搞的,还是我操作问题!!!点了“写新文章”,结果编辑界面还是上一篇文章的内容,就没注意,清除开始写新的,结果还真真修改了以前的文章!纠结要不要重写,就问了下客服,说没办法,要么试着百度下原标题或网址,看有没有快照什么的。我擦擦..

后来不抱希望的搜索了下,百度没找到,google找到了,不过是另一个网站转载了,好吧,就不怪你侵权了哈哈…(偷偷告诉你,被人转载了还有点儿小高兴^_^)

事件分发机制view篇已经完结,哪些说的不对的地方多多指出。建议先了解上篇 Android事件分发机制源码畅游解析(View篇) ,因为最终执行的还是view中的内容。

本篇继续基于APILevel 25(7.1.1) 源码,理解为先、各版本代码可能有差别,核心部分是一致的。

1、找出事件分发的流程、循序

好了,接力开始,本文接着解析事件分发机制源码,上篇文章已经说了view中事件是从dispatchTouchEvent开始传递的,其实我们知道,一个界面至少有Activity、ViewGroup、View。那么我们就会有个疑问,触摸事件只是传给链条上某一个吗?要么是到达了ViewGroup,要么是View?

我们不妨胡乱猜测一下:比如直接到button,button直接会触发onclick,可是当view是一个textview时,点击事件怎么办,contain它的viewgroup不可能不要事件吧。那会不会是从View->ViewGroup向上传递事件呢?

行了,先别乱猜了,我们测试一下,基于上篇,先自定义一个MyLinearLayout(看起来下面的代码有点儿多,其实只用大概瞟一眼写了什么就行…)

1-1、MyLinearLayout

public class MyLinearLayout extends LinearLayout {
private static final String TAG = MyLinearLayout.class.getSimpleName();

public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "dispatchTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "dispatchTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "dispatchTouchEvent ACTION_UP");
break;

default:
break;
}
return super.dispatchTouchEvent(ev);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onTouchEvent ACTION_UP");
break;

default:
break;
}

return super.onTouchEvent(event);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "onInterceptTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.i(TAG, "onInterceptTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.i(TAG, "onInterceptTouchEvent ACTION_UP");
break;

default:
break;
}

return super.onInterceptTouchEvent(ev);
}

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
Log.i(TAG, "requestDisallowInterceptTouchEvent ");
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}


1-2、button代码

@SuppressLint("AppCompatCustomView")
public class MyButton extends Button {
private static final String TAG = MyButton.class.getSimpleName();

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

@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.e(TAG, "onTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.e(TAG, "onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, "onTouchEvent ACTION_UP");
break;
}
return super.onTouchEvent(event);
}

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.e(TAG, "dispatchTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.e(TAG, "dispatchTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, "dispatchTouchEvent ACTION_UP");
break;
}
return super.dispatchTouchEvent(event);
}
}


1-3、MainActivity布局文件

<?xml version="1.0" encoding="utf-8"?>
<com.hds.viewevent.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hds.viewevent.MainActivity">

<com.hds.viewevent.MyButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</com.hds.viewevent.MyLinearLayout>


1-4、MainActivity代码

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("button", "onclick");
}
});
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e("button", "onTouch");
return false;
}
});
MyLinearLayout myLinearLayout = (MyLinearLayout) findViewById(R.id.main_layout);
myLinearLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("MyLinearLayout", "onTouch");
return false;
}
});
myLinearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("MyLinearLayout", "onclick");
}
});
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "dispatchTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "dispatchTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "dispatchTouchEvent ACTION_UP");
break;

default:
break;
}
return super.dispatchTouchEvent(ev);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "onTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "onTouchEvent ACTION_UP");
break;

default:
break;
}
return super.onTouchEvent(event);
}

}


1-5、点击button测试

点了几次,点了一次完美的,^_^

看到了吧,事件是从Activity->ViewGroup->View的流程



2、先从ViewGroup说起

有人问了,为什么不直接从上到下呢。从上到下也可以,不过我们是源码解析,那样这篇文章将会无比巨长,可能到中途已经忘了开始是什么。我们将事件顺序反过来,从View->ViewGroup->Activity,就好比一个问题根源的寻找过程。

就来先讨论ViewGroup,根据上图的顺序,先来看dispatchTouchEvent

public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}

// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}

boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;

// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}

// Check for interception.
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;
}

// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}

//1.ACTION_CANCEL时,canceled=true是必然的。
//2.如果当前ViewGroup正处于detach状态,那么mPrivateFlags 的PFLAG_CANCEL_NEXT_UP_EVENT被置位。
//resetCancelNextUpFlag(this)也会为return true。
//3.非1、2的情况下,canceled = false;
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;

// 查看mGroupFlags中的FLAG_SPLIT_MOTION_EVENTS位设置情况,看ViewGroup是否可以支持事件适时传给多个子view
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
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 actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;

// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);

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;
}

if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}

newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
//child的mPrivateFlags中的PFLAG_CANCEL_NEXT_UP_EVENT位归0重置。
resetCancelNextUpFlag(child);
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;
}

// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}

if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}

// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
// 没有子View接收事件,ViewGroup就不能高看自己了,作为普通view处理事件吧。
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it.  Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}

// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}

if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}


1、第18-24 部分,当事件是MotionEvent.ACTION_DOWN,做一些初始化的东西,如注释的英文所示:当开始一个touch操作时,清除之前所有的状态。可能由于switch, ANR, or some other state change,framework可能已经丢掉了之前操作的up和cancel事件

// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}


cancelAndClearTouchTargets()方法,取消和清除所有的touch target

private void cancelAndClearTouchTargets(MotionEvent event) {
if (mFirstTouchTarget != null) {
boolean syntheticEvent = false;
//当DetachedFromWindow时event = null
if (event == null) {
final long now = SystemClock.uptimeMillis();
event = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
syntheticEvent = true;
}

for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
//view.mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVENT位设置为0
resetCancelNextUpFlag(target.child);
//第二个参数是true,意味传到onTouchEvent时,MotionEvent.Action_CANCEL,事件进入取消的case中,后面会详细分析
dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
}
//进入看,将TouchTarget链条中的都recycle掉,目的是每一个target中的child=null;最重要的是初始化mFirstTouchTarget = null;
clearTouchTargets();

if (syntheticEvent) {
event.recycle();
}
}
}


resetTouchState()取消一个touch状态,FLAG_DISALLOW_INTERCEPT位归0等。

2、第28-41 段部分,只要是 MotionEvent.ACTION_DOWN就可以进入,FLAG_DISALLOW_INTERCEPT是requestDisallowInterceptTouchEvent可动态设置的标识位,最终影响是否能走到onInterceptTouchEvent。一般disallowIntercept都是false,会走入onInterceptTouchEvent

//如果去看源码,注释无比巨长,其实就是当return true时,事件将不会传到子view中,大家可以根据本篇开头的demo中改成true试试。

public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}


3、第89 行,preorderedList 得到有顺序的view,根据layout文件的先后顺序和addView的先后顺序。最先被加入的是0,接着是1,2,3…,后面循环取出倒序是因为我们肯定想要点中的是最靠近用户的一层view。

4、第111 行,判断处于循环中的view是否可以接收(是否处于visiable、animation中)事件;事件发生地(x/y)是否在view中。

5、第117 行,newTouchTarget = getTouchTarget(child);查看child是否在TouchTarget的链条中,在返回target,不再返回null。

/**
* Gets the touch target for specified child view.
* Returns null if not found.
*/
private TouchTarget getTouchTarget(@NonNull View child) {
for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
if (target.child == child) {
return target;
}
}
return null;
}


6、第126 行,if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign))重点来看一下,哎呀,源代码好长。主要流程就是当child=null时,事件会走到ViewGroup的父类View.dispatchTouchEvent中;否则会都到child.dispatchTouchEvent的。然后的就跟上一篇(View篇)一样。

所以如果126行if判断成功,即有view处理了此事件。那么addTouchTarget就会执行,target.child = child,mFirstTouchTarget = target;mFirstTouchTarget赋值。

//根据情况将事件分发dispatchTouchEvent,所以有可能是分发给child,有可能是自我调用了。

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;

//cancel = true的时候,分发的结果就是在view的onTouchEvent中取消状态、恢复初始状态的操作。
// Canceling motions is a special case.  We don't need to perform any transformations
// or filtering.  The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}

// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}

// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);

handled = child.dispatchTouchEvent(event);

event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}

// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}

handled = child.dispatchTouchEvent(transformedEvent);
}

// Done.
transformedEvent.recycle();
return handled;
}


如果恰好是点击了一个类button,那么根据上面分析mFirstTouchTarget !=null,那么在ACTION_DOWN之后的事件(如MOVE/UP)就会在第28 行判断走到else,结果就是intercepted = true;

又导致第62 行不能进入,此时61 行alreadyDispatchedToNewTouchTarget = false。

仔细分析你会发现最终会走到184 行,好嘛,还是target.child = child,child.dispatchTouchEvent。这个child还是在上一步addTouchTarget时候已接收ACTION_DOWN事件时保存的。

3、总结流程

上面说了那么多,说的短吧就不叫源码解析,说的细吧,说着说着都不知道飞到哪儿去了。其实运行下开头的demo,理解下事件的流程,然后再分析,会有更深入的理解。毕竟实践和直观现场才最能代入剧情。伪代码如下

ViewGroup.java
...
public boolean dispatchTouchEvent(MotionEvent ev) {
...
if(onInterceptTouchEvent(ev)){
super.dispatchTouchEvent(event);//自身
} else {
if(child){//有可以接收事件的child
child.dispatchTouchEvent(event);
}else{
super.dispatchTouchEvent(event);//自身
}
}
...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: