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

Android触摸事件派发机制源码分析之ViewGroup

2017-03-06 17:22 555 查看
紧接上篇

view分析

,开篇上代码

首先是activity的代码如下

package com.sparkhuu.testevent;

import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import junit.framework.Test;

import java.io.Serializable;

public class MainActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener {
public static final String TAG = "test";
RelativeLayout rl_layout;
TestButton btn_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl_layout = (RelativeLayout) this.findViewById(R.id.rl_layout);
btn_view = (TestButton) this.findViewById(R.id.btn_view);

btn_view.setOnTouchListener(this);
rl_layout.setOnTouchListener(this);

btn_view.setOnClickListener(this);
rl_layout.setOnClickListener(this);
}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.i(TAG, "OnTouchListener----onTouch----action" + motionEvent.getAction() + "-----" + view);
return false;
}

@Override
public void onClick(View view) {
Log.i(TAG, "OnClickListener---onClick---" + view);
}
}


再来看看我们自定义的TestRelativeLayout代码如下

package com.sparkhuu.testevent;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

/**
* author:sparkhuu
* email:sparkhuu@gmail.com
*/

public class TestRelatvieLayout extends RelativeLayout {
public TestRelatvieLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.i(MainActivity.TAG, "TestRelatvieLayout -- onInterceptTouchEvent----action" + ev.getAction());
return super.onInterceptTouchEvent(ev);
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i(MainActivity.TAG, "TestRelatvieLayout -- dispatchTouchEvent----action" + ev.getAction());

return super.dispatchTouchEvent(ev);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(MainActivity.TAG, "TestRelatvieLayout -- onTouchEvent----action" + event.getAction());

return super.onTouchEvent(event);
}
}


再来看下TestButton中的代码如下

package com.sparkhuu.testevent;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

/**
* author:sparkhuu
* email:sparkhuu@gmail.com
*/

public class TestButton extends Button {
public TestButton(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.i(MainActivity.TAG, "TestButton ----dispatchTouchEvent -- action" + event.getAction());
return super.dispatchTouchEvent(event);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(MainActivity.TAG, "TestButton ----onTouchEvent -- action" + event.getAction());
return super.onTouchEvent(event);
}
}


再来看下xml中的代码如下

<?xml version="1.0" encoding="utf-8"?>
<com.sparkhuu.testevent.TestRelatvieLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.sparkhuu.testevent.MainActivity"
>

<com.sparkhuu.testevent.TestButton
android:id="@+id/btn_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</com.sparkhuu.testevent.TestRelatvieLayout>


运行结果如下



从log可以看出事件传递是ViewGropd的dispatchTouchEvent—>ViewGrop的onInterceptTouchEvent—>View的dispatchTouchEvent接着就是view的事件派发流程,上一篇说过了,也就是每次点击view时事件派发每一个down,move,up的顺序都是先出发父控件的dispatchTouchEvent—>onInterceptTouchEvent然后才是view控件的事件派发

那么点击Button外的部分log信息如下



可以发现事件和view的事件派发类似,但不同的是down和move在dispatchTouchEvent后多了一个onInterceptTouchEvent而up事件却没有,带着疑问,我们来看下源码分析

首先从ViewGroup的dispatchTouchEvent看起,如下

@Override
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);
}

// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;

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

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.
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,开端MotionEvent.ACTION_DOWN,因为MotionEvent.ACTION_DOWN是一系列事件的开端,当是MotionEvent.ACTION_DOWN进行一些初始化操作,从注释也可以看出,将清除以往的Touch状态然后开始新的手势,在cancelAndClearTouchTargets方法中将mFirstTouchTarget设置为null,接着在resetTouchState方法中重置touch状态

在dispatchTouchEvent中通过intercepted变量来标记ViewGroup是否需要对Touch事件进行拦截,if (actionMasked == MotionEvent.ACTION_DOWN

|| mFirstTouchTarget != null)表示已经找到能够接受touch事件的目标组件则if成立,反之if不成立然后将intercepted变量置为true,即拦截事件,而当if条件成立时,则判断disallowIntercept(禁止拦截)标识位,而这个标识位通过下面这个方法进行赋值

@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
// We're already in this state, assume our ancestors are too
return;
}

if (disallowIntercept) {
mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
} else {
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
}

// Pass it up to our parent
if (mParent != null) {
mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}


所以可以在其他地方调用requestDisallowInterceptTouchEvent从而禁止执行是否需要拦截的判断,当disallowIntercept为true(禁止拦截判断)时则intercepted直接为false,否则调用onInterceptTouchEvent,下面来看下ViewGroup的onInterceptTouchEvent方法

/**
* Implement this method to intercept all touch screen motion events.  This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* <p>Using this function takes some care, as it has a fairly complicated
* interaction with {@link View#onTouchEvent(MotionEvent)
* View.onTouchEvent(MotionEvent)}, and using it requires implementing
* that method as well as this one in the correct way.  Events will be
* received in the following order:
*
* <ol>
* <li> You will receive the down event here.
* <li> The down event will be handled either by a child of this view
* group, or given to your own onTouchEvent() method to handle; this means
* you should implement onTouchEvent() to return true, so you will
* continue to see the rest of the gesture (instead of looking for
* a parent view to handle it).  Also, by returning true from
* onTouchEvent(), you will not receive any following
* events in onInterceptTouchEvent() and all touch processing must
* happen in onTouchEvent() like normal.
* <li> For as long as you return false from this function, each following
* event (up to and including the final up) will be delivered first here
* and then to the target's onTouchEvent().
* <li> If you return true from here, you will not receive any
* following events: the target view will receive the same event but
* with the action {@link MotionEvent#ACTION_CANCEL}, and all further
* events will be delivered to your onTouchEvent() method and no longer
* appear here.
* </ol>
*
* @param ev The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
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;
}


这里默认返回false, 也就是intercepted返回false,这表明在ViewGroup的dispatchTouchEvent中默认首先调用了onInterceptTouchEvent(没有在其他地方调用requestDisallowInterceptTouchEvent)

通过标记和action检查cancel赋值给变量canceled

// Check for cancelation.

final boolean canceled = resetCancelNextUpFlag(this)

|| actionMasked == MotionEvent.ACTION_CANCEL;

然后定义split变量, final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;

默认值为true,作用是把事件分发给多个子view,同样在viewGroup中提供了方法设置,代码如下

/**
* Enable or disable the splitting of MotionEvents to multiple children during touch event
* dispatch. This behavior is enabled by default for applications that target an
* SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer.
*
* <p>When this option is enabled MotionEvents may be split and dispatched to different child
* views depending on where each pointer initially went down. This allows for user interactions
* such as scrolling two panes of content independently, chording of buttons, and performing
* independent gestures on different pieces of content.
*
* @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
*              child views. <code>false</code> to only allow one child view to be the target of
*              any MotionEvent received by this ViewGroup.
* @attr ref android.R.styleable#ViewGroup_splitMotionEvents
*/
public void setMotionEventSplittingEnabled(boolean split) {
// TODO Applications really shouldn't change this setting mid-touch event,
// but perhaps this should handle that case and send ACTION_CANCELs to any child views
// with gestures in progress when this is changed.
if (split) {
mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
} else {
mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
}
}


接着 if (!canceled && !intercepted) 判断表明,事件不是Action_cancel并且ViewGroup的拦截标识位intercepted为false(不拦截)则会进入代码

接着 if (actionMasked == MotionEvent.ACTION_DOWN

|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)

|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) 这个环节处理action_down比较繁琐,首先 if (newTouchTarget == null && childrenCount != 0)判断childrenCount不为0,然后 final ArrayList preorderedList = buildTouchDispatchChildList();

拿到了view的list集合preorderedList,接着 for (int i = childrenCount - 1; i >= 0; i–) {

倒序遍历所有得子view(这是因为preorderedList中的顺序是按照addView或者xml布局中的顺序来的,后add进来的子view,会因为Android的ui后刷新机制显示在上层,假如点击的地方有2个子view都包含点击的坐标,那么后添加到布局中的子view会先响应事件)

接着 newTouchTarget = getTouchTarget(child);

去查找当前子view是否在mFirstTouchTarget.next这条target链条中的某一个target中,如果在则返回这个target,否则返回null,在for (int j = 0; j < childrenCount; j++) {

if (children[childIndex] == mChildren[j]) {

mLastTouchDownIndex = j;

break;

}

}中说明找到了接受touch事件的子view,即newTouchTarget,既然找到了那么 break跳出for循环代码,如果没有找到则 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {

这里包含的代码主要是调用dispatchTransformedTouchEvent将touch事件传递给特定的子view。该方法中为一个递归,会递归调用dispatchTouchEvent在dispatchTouchEvent中如果View为ViewGroup并且Touch没有被拦截那么递归调用dispatchTouchEvent如果子view为view那么就会调用其onTouchEvent,dispatchTransformedTouchEvent返回true表示事件被view销毁掉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;

}给newTouchTarget赋值,

下面来分析下dispatchTransformedTouchEvent

/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;

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


上面说到在dispatchTouchEvent中调用下面来分析下dispatchTransformedTouchEvent将事件派发给子view,可以看到第三个参数view在dispatchTouchEvent调用dispatchTransformedTouchEvent很多处地方有的有值有的为null。在这段源码中进行了解释,可以发现在dispatchTransformedTouchEvent很多处地方对view进行了非null判断,当child == null 时,会讲touche事件传递给ViewGroup自身的dispatchTouchEvent处理,即 handled = super.dispatchTouchEvent(event);

当child !=null 时,会调用 handled = child.dispatchTouchEvent(event);

总结:

1,Android事件派发是先传递到最顶级的ViewGroup,再由ViewGroup递归传递到View

2,在ViewGroup中可以通过onIntercepttouchEvent方法对事件进行拦截,返回true代表拦截,false则不拦截

3,子View中如果将事件销毁掉,ViewGroup中将无法接受到任何事件

actitivy分析
[Activity分析](http://blog.csdn.net/eandroidhu/article/details/60868806)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 源码