在公司的项目中主界面用了侧滑菜单栏(DrawerLayout),类似滴滴打车,当然还有很多其他的软件都使用这样的布局。用本篇对DrawerLayout一些学习进行记录。
Drawable出现了事件穿透
1.界面布局
类似滴滴打车的侧滑界面,其中有一部分是空白区域,当点击空白区域,会将点击事件传递到被遮挡的主布局上,现象:如果是类似滴滴,主界面是地图的话,手指在侧滑栏空白区域移动,主界面地图可以拖动。
2.解决方法
在侧滑栏的根布局添加android:clickable=”true” 属性。代码示例如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 主界面布局-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- 侧滑栏布局,需要将android:clickable属性设置为true -->
<LinearLayout
android:layout_width="240dp"
android:layout_height="match_parent"
android:gravity="start|left"
android:clickable="true">
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
3.从Android事件分发机制来分析
3.1 点击事件传递规则
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;
if (onInterceptTouchEvent(ev)) {
consume = onTouchEvent(ev);
} else {
consume = child.dispatchTouchEvent(ev);
}
return consume;
}
ViewGroup会调用onInterceptTouchEvent方法进行拦截,如果被拦截则调用自身的onTouchEvent方法进行处理,如果不拦截则交由子元素进行后续分发/处理。
一个点击事件产生后,传递规则:Activity->Window->View,如果View的onTouchEvent方法返回false,则它的父容器的onTouchEvent方法会被调用,以此类推直到返回到Activity的onTouchEvent方法。
3.2 源码分析
Activity的dispatchTouchEvent方法如下:
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
点击事件由Activity传递给Window,如果点击事件被消费,则返回true并结束,如果Window没有消费事件,则调用Activity自身的onTouchEvent方法。
Window源码
/**
* Used by custom windows, such as Dialog, to pass the touch screen event
* further down the view hierarchy. Application developers should
* not need to implement or call this.
*
*/
public abstract boolean superDispatchTouchEvent(MotionEvent event);
Window是一个抽象类,superDispatchTouchEvent也是抽象方法,在Window的类注释中,可以看到它的唯一实现类是PhoneWindow,如下:
/**
* Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.
*
* <p>The only existing implementation of this abstract class is
* android.view.PhoneWindow, which you should instantiate when needing a
* Window.
*/
public abstract class Window {
.....
}
PhoneWindow源码
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
在Window实现类中,PhoneWindow将点击事件传递给DecorView(继承FrameLayout),至此,事件已经从Activity传递到了View。
ViewGroup源码:
// 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;
}
首先事件到达ViewGroup的dispatchTouchEvent方法,先进行拦截检查:
1.事件为按下事件;
2.mFirstTouchTarget不为空;
则表示进行拦截检查,mFirstTouchTarget后续是会指向ViewGroup处理事件成功的子元素,如果事件来Move或者Up,一旦之前ViewGroup已经拦截,则不会再调用onInterceptTouchEvent方法,因为mFirstTouchTarget为空。如果事件不被拦截或者不被取消,那么接下会遍历ViewGroup的子元素
// 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 (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
....
}
这个dispatchTransformedTouchEvent方法会对child参数进行判断,如果child为空,则调用父容器的onTouch方法,如果不为空则调用child的onTouch方法
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;
}
如果没有子元素或者子元素没有处理点击事件,则事件转给ViewGroup的父类View进行处理。
View源码:
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
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;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
如果View设置了OnTouchListener,它的优先级最大,如果它的onTouch方法返回true,则不会执行onTouchEvent方法。接下来看onTouchEvent方法:
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
...
如果View是不可用状态下,依旧会消耗点击事件,如果View的CLICKABLE,LONG_CLICKABLE, CONTEXT_CLICKABLE,其中有一个为true则会消耗点击事件。至此,事件传递已经完成分析。那开头说事件穿透的解决方法是android:clickable=”true”,根据源码分析,这样也有了根据了。