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

Android触摸屏ViewGroup事件派发机制详解与源码分析

2016-04-12 09:47 816 查看
同样的还是参考了一些文章,在我上一篇文章中的头部:

http://blog.csdn.net/lijinhua7602/article/details/51122214

2 基础实例现象

2-1 例子

这个例子布局等还和上一篇的例子相似,只是重写了Button和LinearLayout而已,具体参见上一篇:

首先我们简单的自定义一个Button(View的子类),再自定义一个LinearLayout(ViewGroup的子类),其实没有自定义任何属性,只是重写部分方法(添加了打印,方便查看)而已,如下:

<?xml version="1.0" encoding="utf-8"?>
<com.example.viewdispatch.ViewGroupLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mylayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<com.example.viewdispatch.ViewGroupTestButton
android:id="@+id/my_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click test" />

</com.example.viewdispatch.ViewGroupLinearLayout>


public class ViewGroupTestButton extends Button {

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

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_down --");
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent--- action_move --");
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_up --");
break;
}
return super.dispatchTouchEvent(event);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "onTouchEvent-- action_down --");
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "onTouchEvent-- action_move --");
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "onTouchEvent--action_up --");
break;
}
return super.onTouchEvent(event);
}
}


public class ViewGroupListenerActivity extends Activity implements View.OnTouchListener, View.OnClickListener {

private ViewGroupLinearLayout mLayout;
private ViewGroupTestButton mButton;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.viewgroup_listener);

mLayout = (ViewGroupLinearLayout) this.findViewById(R.id.mylayout);
mButton = (ViewGroupTestButton) this.findViewById(R.id.my_btn);

mLayout.setOnTouchListener(this);
mButton.setOnTouchListener(this);

mLayout.setOnClickListener(this);
mButton.setOnClickListener(this);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_down --" + v);
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_move --" + v);
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "OnTouchListener--onTouch-- action_up --" + v);
break;
}
return false;
}

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


2-2 运行现象



分析:

你会发现这个结果好惊讶吧,点击了Button却先执行了ViewGroupLinearLayout(ViewGroup)的dispatchTouchEvent,接着执行ViewGroupLinearLayout(ViewGroup)的onInterceptTouchEvent,接着执行ViewGroupTestButton(ViewGroupLinearLayout包含的成员View)的dispatchTouchEvent,接着就是View触摸事件的分发流程,上一篇已经讲过了。也就是说当点击View时事件派发每一个down,up的action顺序是先触发最父级控件(这里为LinearLayout)的dispatchTouchEvent->onInterceptTouchEvent->然后向前一级传递(这里就是传递到Button View)。

那么继续看,当直接点击除Button以外的其他部分时打印如下:



分析:你会发现一个奇怪的现象,派发ACTION_DOWN(action=0)事件时顺序为dispatchTouchEvent->onInterceptTouchEvent->onTouch->onTouchEvent,而接着派发ACTION_UP(action=1)事件时与上面顺序不同的时竟然没触发onInterceptTouchEvent方法。这是为啥呢?我也纳闷,那就留着下面分析源码再找答案吧,先记住这个问题。

有了上面这个例子你是不是发现包含ViewGroup与View的事件触发有些相似又有很大差异吧(PS:在Android中继承View实现的控件已经是最小单位了,也即在XML布局等操作中不能再包含子项了,而继承ViewGroup实现的控件通常不是最小单位,可以包含不确定数目的子项)。具体差异是啥呢?咱们类似上篇一样,带着这个实例疑惑去看源码找答案吧。

ViewGroup触摸屏事件传递源码分析

从ViewGroup的dispatchTouchEvent方法说起

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// mInputEventConsistencyVerifier是调试用的,不会理会
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// 第1步:是否要分发该触摸事件
// onFilterTouchEventForSecurity()表示是否要分发该触摸事件。
// 如果该View不是位于顶部,并且有设置属性使该View不在顶部时不响应触摸事件,则不分发该触摸事件,即返回false。
// 否则,则对触摸事件进行分发,即返回true。
// 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);
}
// 该View被遮蔽,并且该View在被遮蔽时不响应点击事件
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// 第2步:检测是否需要清空目标和状态
// 如果是ACTION_DOWN(即按下事件),则清空之前的触摸事件处理目标和状态。
// 这里的情空状态包括:
// (01) 清空mFirstTouchTarget链表,并设置mFirstTouchTarget为null。
//mFirstTouchTarget是"接受触摸事件的View"所组成的单链表
// (02) 清空mGroupFlags的FLAG_DISALLOW_INTERCEPT标记
//如果设置了FLAG_DISALLOW_INTERCEPT,则不允许          ViewGroup对触摸事件进行拦截。
// (03) 清空mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVEN标记
// 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 = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(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;
}


第一步,ACTION_DOWN进行处理。

30-36行,ACTION_DOWN(即按下事件),则清空之前的触摸事件处理目标和状态,清空mFirstTouchTarget链表,并设置mFirstTouchTarget为null, 清空mGroupFlags的FLAG_DISALLOW_INTERCEPT标记,清空mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVEN标记

第二步,40-53行,检查是否要拦截,设置intercepted。

if (actionMasked == MotionEvent.ACTION_DOWN

|| mFirstTouchTarget != null) 是按下事件,或者这个Touch的目标组件不为null,进入到里面,否则就设置intercepted为true,我们来看进入到里面的情况,这里有一个变量FLAG_DISALLOW_INTERCEPT,这个是检查是否禁止拦截标记,来看一下这个变量相关的方法:

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(true); 阻止ViewGroup对其MOVE或者UP事件进行拦截,则intercepted直接设置为false,否则调用onInterceptTouchEvent(ev)方法,然后将结果赋值给intercepted,来看一下 onInterceptTouchEvent(ev)方法,

public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}


默认的onInterceptTouchEvent方法只是返回了一个false,也即intercepted=false。所以可以说明上面例子的部分打印(dispatchTouchEvent->onInterceptTouchEvent->onTouchEvent),这里很明显在ViewGroup的dispatchTouchEvent()中默认(不在其他地方调用requestDisallowInterceptTouchEvent方法设置FLAG_DISALLOW_INTERCEPT禁止拦截标记时这个默认为false,要进行拦截,只不过这里面的ViewGroup里面onInterceptTouchEvent方法默认返回false,即intercepted=false)。

第三步,检查canceled变量是否被取消。

对于ACTION_DOWN而言,mPrivateFlags的PFLAG_CANCEL_NEXT_UP_EVENT位肯定是0;因此,canceled=false,所以没有被取消

第四步,检查split变量

默认是true,作用是否把事件分发给当前ViewGroup的子View和子ViewGroup,这个同样在ViewGroup中提供了public的方法设置,如下:

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


事件分发步骤中关于ACTION_DOWN的特殊处理

if (!canceled && !intercepted)判断表明,事件不是ACTION_CANCEL并且ViewGroup的拦截标志位intercepted为false(不拦截)则会进入其中。进入到里面首先看第一个if条件:

对于ACTION_DOWN,actionIndex肯定是0,就会进入到if里面,接下来就是处理点击事件:这里面引用到了博客里面的内容:http://blog.csdn.net/yanbober/article/details/45912661

ViewGroup触摸屏事件传递总结

Android事件分发是先传递到ViewGroup,再由ViewGroup传递到View的。

在ViewGroup中可以通过onInterceptTouchEvent方法对事件传递进行拦截,onInterceptTouchEvent方法返回true代表不允许事件继续向子View传递,返回false代表不对事件进行拦截,默认返回false。

子View中如果将传递的事件消费掉,ViewGroup中将无法接收到任何事件。

实例现象

现在我们就能解释上一篇中的TestButton里面的dispatchTouchEvent返回false的情况,执行了linearlayout的onTouch,因为TestBuatton里面的dispatchTouchEvent返回false表示对当前的view不进行分发事件,所以TestBoutton所有的事件都接受不到了

将ViewGroupLinearLayout的dispatchTouchEvent改为true,其他基础代码不变:

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_down --");
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_move --");
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout dispatchTouchEvent--action_up --");
break;
}
return true;
}


点击Button或者之外都是一样的



不进行事件的分发,所以只执行当前ViewGorup的dispatchTouchEvent方法

现在我们进行拦截,把ViewGroupLinearLayout的onInterceptTouchEvent返回为true,其他基础保持不变:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_down --");
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_move --");
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "ViewGroupLinearLayout onInterceptTouchEvent--action_up --");
break;
}
return true;
}


点击Button或者Button之外:



分析:因为 我们这里面进行了拦截,所以不会执行Button的任何方法,只会执行当前类的OnTouchEvent和onTouch方法

如何不拦截也,我们只需要重写子类View的dispatchTouchEvent方法,利用requestDisallowInterceptTouchEvent(true)设置不要进行拦截,处理ViewGroupTestButton的dispatchTouchEvent,其他代码不变:

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_down --");
break;
case MotionEvent.ACTION_MOVE:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent--- action_move --");
break;
case MotionEvent.ACTION_UP:
Log.i(ListenerActivity.TAG, "dispatchTouchEvent-- action_up --");
break;
}
return super.dispatchTouchEvent(event);
}




分析可以看到ViewGroupLinearLayout的onToucheEvent没有执行,更多请读者自选尝试
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: