为什么需要View事件分发与绘制

  在做android开发的过程中,Android提供的控件不一定全能满足我们的需求,因此我们需要去自定义属于我们自己的控件。如为定义一些控件的属性,样式,功能等。为了实现这些效果。我们有必要先了解一下自定义控件时候经常需要重写的几个函数,这几个函数涉及到了View事件的分发和绘制。

View的事件分发

  View的事件分发是指当我们在屏幕上产生点击后,产生了一个触摸事件,这个事件通过层层分发最后到相应的view去执行。要知道事件是怎么分发的,首先我们需要知道Android中显示出来的View是怎么组成的。

(1)View的组成

  在Android中,所有的控件都是View,而在一个页面上这些View都是以树形结构进行组成,以一个View为根节点,根节点下依次是儿子节点,孙子节点等。这些节点可以是View,也可以上ViewGroup。当我们点击屏幕后,这些系统通过TW到驱动到Framwork处理,将事件封装成一个MontionEvent事件。如在一个Activity中,这个Activity接受到一个触摸事件则会有一个MontionEvent从页面的根View开始,进行层层分发,开始寻找能够处理这个事件的View。

(2)事件分发需要重写的几个方法

在自定义View中,通常有几种情况:
1、继承一个已有的View。如继承一个TextView之类的。
2、直接继承一个View。
3、继承一个ViewGroup。
其中,在1和2 提供了两个方法
dispatchTouchEvent(MotionEvent ev):用来进行事件的分发
onTouchEvent(MotionEvent ev):用来处理点击事件。
而在3中多出了一个
onInterceptTouchEvent(MotionEvent ev):用来进行事件的拦截。
先来看看在View的dispatchTouchEvent(MotionEvent ev)方法进行了什么。

/** * 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) {            android.util.SeempLog.record(3);            // Defensive cleanup for new gesture            stopNestedScroll();        }        if (onFilterTouchEventForSecurity(event)) {            //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是否需要处理这个事件。true则代表消费掉这个事件。同时注意

 if (onFilterTouchEventForSecurity(event)) {            //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;            }        }

可以看出 OnTouchListener 是优先于onTouchEvent处理的。接下来看看View中的onTouchEvent方法。

public boolean onTouchEvent(MotionEvent event) {        android.util.SeempLog.record(3);        final float x = event.getX();        final float y = event.getY();        final int viewFlags = mViewFlags;        final int action = event.getAction();        //viewFlags 的值为CLICKABLE 或者LONG_CLICKABLE或者CONTEXT_CLICKABLE 这个事件就讲被消费,消费的方式根据对应的值处理        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;                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {                        // take focus if we don't have it already and we should in                        // touch mode.                        boolean focusTaken = false;                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {                            focusTaken = requestFocus();                        }                        if (prepressed) {                            // The button is being released before we actually                            // showed it as pressed. Make it show the pressed                            // state now (before scheduling the click) to ensure                            // the user sees it.                            setPressed(true, x, y);                       }                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {                            // This is a tap, so remove the longpress check                            removeLongPressCallback();                            // Only perform take click actions if we were in the pressed state                            if (!focusTaken) {                                // Use a Runnable and post this rather than calling                                // performClick directly. This lets other visual state                                // of the view update before click actions start.                                if (mPerformClick == null) {                                    mPerformClick = new PerformClick();                                }                                if (!post(mPerformClick)) {                                    performClick();                                }                            }                        }                        if (mUnsetPressedState == null) {                            mUnsetPressedState = new UnsetPressedState();                        }                        if (prepressed) {                            postDelayed(mUnsetPressedState,                                    ViewConfiguration.getPressedStateDuration());                        } else if (!post(mUnsetPressedState)) {                            // If the post failed, unpress right now                            mUnsetPressedState.run();                        }                        removeTapCallback();                    }                    mIgnoreNextUpEvent = false;                    break;......                case MotionEvent.ACTION_CANCEL:                    setPressed(false);                    removeTapCallback();                    removeLongPressCallback();                    mInContextButtonPress = false;                    mHasPerformedLongPress = false;                    mIgnoreNextUpEvent = false;                    break;......            }            return true;        }        return false;    }

接着在看看在ViewGroup中的dispatchTouchEvent 有何不同。

         // 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. //下面没有处理该事件的View 则有该控件拦截                intercepted = true;            }

首先对是否拦截该事件进行了处理。在onInterceptTouchEvent中,默认了不进行拦截。

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

接下来看看dispatchTouchEvent 对其中的子View处理。
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);                    }

在for循环中,遍历ViewGroup的子View,一旦遍历到合适的View 则将事件传递下去。事件通过dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign) 进行传递。

final int oldAction = event.getAction();        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {            event.setAction(MotionEvent.ACTION_CANCEL);            if (child == null) {                handled = super.dispatchTouchEvent(event); //子View不存在,调用父类的dispatch,ViewGroup继承于View 即调用View的dispatch            } else {                handled = child.dispatchTouchEvent(event);//子View存在,调用子View的dispatchTouchEvent,如果子Vie可ViewGropu可View            }            event.setAction(oldAction);            return handled;        }

综上可知,ViewGroup与View的事件传递规律如下:
1、ViewGroup 通过dispatchTouchEvent 来分发事件,如果该事件被拦截,则调用父类的onTouchEvent进行处理,不拦截则将事件传递给子View处理,子View则调用自己onTouchEvent进行处理。如果子View不进行处理,则会返回给ViewGroup 进行处理。

View的绘制

  View的绘制是通过三个方法来进行。分别是测量、布局以及绘制。在view中分别对应了Measure(int widthMeasureSpec, int heightMeasureSpec), layout(int l, int t, int r, int b)以及draw(Canvas canvas)方法。
   如上文所说,整个视图是一个树形结构,View的绘制也是重根节点开始进行递归。绘制的发起者为ViewRootImpl.Java类的performTraversals()函数展开。通过判断是否需要measure、layout、draw来决定View的绘制。通常会调用到View的onMeasure,onLayout(ViewGroup中进行重写),以及onDrwa方法。

(1)onMeasure方法

  在View的绘制中onMeadure方法主要用于对自身宽高的测量。在View.java中,可以看到

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));    }

这里的意图是在onMeasure中调用了setMeasuredDimension函数去set值。

  protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {        boolean optical = isLayoutModeOptical(this);        if (optical != isLayoutModeOptical(mParent)) {            Insets insets = getOpticalInsets();            int opticalWidth  = insets.left + insets.right;            int opticalHeight = insets.top  + insets.bottom;            measuredWidth  += optical ? opticalWidth  : -opticalWidth;            measuredHeight += optical ? opticalHeight : -opticalHeight;        }        setMeasuredDimensionRaw(measuredWidth, measuredHeight);    }private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {        mMeasuredWidth = measuredWidth;        mMeasuredHeight = measuredHeight;        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;    }

很明显,这里去设置了View的宽和高。再来看看作为参数的getDefaultSize具体做了什么。这个函数中分别以getSuggestedMinimumWidth()和widthMeasureSpec作为参数。先来分析getDefaultSize

public static int getDefaultSize(int size, int measureSpec) {        int result = size;        int specMode = MeasureSpec.getMode(measureSpec);//测量模式        int specSize = MeasureSpec.getSize(measureSpec);//测量大小        switch (specMode) {        case MeasureSpec.UNSPECIFIED:            result = size;            break;        case MeasureSpec.AT_MOST:        case MeasureSpec.EXACTLY:            result = specSize;            break;        }        return result;    }

在getDefaultSize出现了specMode,在MeasureSpec类中,一共有三种模式
public static final int UNSPECIFIED = 0 << MODE_SHIFT; //父容器不做约束,View可任意大小
public static final int EXACTLY = 1 << MODE_SHIFT;//父容器确定view的宽高。
public static final int AT_MOST = 2 << MODE_SHIFT;//对应于wrap_content属性,不能超过父容器
再来看看getSuggestedMinimumWidth()。

return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());

如果有背景则返回mMinWidth 否则返回mMinWidth 与Drawable宽度的最大值。当然在getMinimumWidth中,Drawable在没设定固有宽度则返回0;

(2)layout方法

  在layout(int l, int t, int r, int b)方法中一共有4个参数。分别表示了该view相对于父容器的左边距,上边距,右边距,下边距。

 public void layout(int l, int t, int r, int b) {        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;        }        int oldL = mLeft;        int oldT = mTop;        int oldB = mBottom;        int oldR = mRight;        boolean changed = isLayoutModeOptical(mParent) ?                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {            onLayout(changed, l, t, r, b);            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;            ListenerInfo li = mListenerInfo;            if (li != null && li.mOnLayoutChangeListeners != null) {                ArrayList listenersCopy =                        (ArrayList)li.mOnLayoutChangeListeners.clone();                int numListeners = listenersCopy.size();                for (int i = 0; i < numListeners; ++i) {                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);                }            }        }        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;    }

这里通过setFrame(l, t, r, b),View将自己在父容器的位置进行了设置。

(3)onDraw方法

  党在重写View的时候,我们可以重写onDraw方法,来实现我们自己绘制。

 /** * Implement this to do your drawing. * * @param canvas the canvas on which the background will be drawn */    protected void onDraw(Canvas canvas) {    }

可以看出,我们可以有自己的draw只要去重写该方法。其实这个方法在View的绘制里也被回调。在View的Draw方法里

public void draw(Canvas canvas)        int saveCount;// Step 1, draw the background, if needed         if (!dirtyOpaque) {            drawBackground(canvas);        }        // skip step 2 & 5 if possible (common case)        final int viewFlags = mViewFlags;        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;        if (!verticalEdges && !horizontalEdges) {            // Step 3, draw the content            if (!dirtyOpaque) onDraw(canvas);            // Step 4, draw the children            dispatchDraw(canvas);            // Overlay is part of the content and draws beneath Foreground            if (mOverlay != null && !mOverlay.isEmpty()) {                mOverlay.getOverlayView().dispatchDraw(canvas);            }            // Step 6, draw decorations (foreground, scrollbars)            onDrawForeground(canvas);            // we're done...            return;        }

1、Draw一个View的时候先要需要则先绘制一个背景。
2、保存canvas层
3、绘制自身内容
4、如果有子元素则绘制子元素
5、绘制效果
6、绘制装饰品
但是第二步和第五步在一般情况下都会被省略掉。
可以看见onDraw方法在第三步被回调。

(4)View绘制总结

  View的绘制包括了measure ,layout,draw几个步骤,同时在这几个步骤中都会onMeasure ,onLayout,onDraw进行了回调。

ViewGroup的绘制

  ViewGroup中,没有measure方法但是提供了measureChildren()和measureChild()方法,这位ViewGroup提供了测量子View的方式。

    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {        final int size = mChildrenCount;        final View[] children = mChildren;        for (int i = 0; i < size; ++i) {            final View child = children[i];            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {                measureChild(child, widthMeasureSpec, heightMeasureSpec);            }        }    }

measureChildren调用measureChild方法让子View进行自我测量。

    protected void measureChild(View child, int parentWidthMeasureSpec,            int parentHeightMeasureSpec) {        final LayoutParams lp = child.getLayoutParams();        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,                mPaddingLeft + mPaddingRight, lp.width);        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,                mPaddingTop + mPaddingBottom, lp.height);        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);    }

在measureChild中由调用了View的measure方法进行了测量。
以上便是View的事件分发与绘制的原理分析,下一章将给出具体的demo来展示怎么通过这几个方法来自定义View。

更多相关文章

  1. 电脑怎么安装安卓系统?安卓(Android)x86 4.4安装方法图文步骤
  2. Android电子牌外接USB读卡器读取内容模拟键盘事件
  3. Android(安卓)通过 JNI 调用 Java 类的构造方法和父类的方法
  4. Android进阶:十二、最简单的方式实现自定义阴影效果
  5. 如何抽取一个通用的Android(安卓)Loading页面快速实现加载功能
  6. java Android(安卓)回调机制的详解
  7. Android(安卓)获取当前应用分配的最大内存和目前使用内存的方法
  8. [Android(安卓)Studio系列(三)]Android(安卓)Studio 编译、同步
  9. Android底部导航栏标签切换: ToolBar+TabLayout+ViewPager+Fragm

随机推荐

  1. Android自动化工具Monkeyrunner使用(五)
  2. Android中Activity的四种启动模式详解
  3. Android Binder
  4. 安卓017ListView & GridView & ScrollView
  5. Android必备:Android Activity的生命周期
  6. Android日志输出单元测试Debug
  7. Android锁定横竖屏、splash,全屏、去除标
  8. Android TextView 中如何使用第三方字体
  9. Windows平台下搭建Android原生C/C++开发
  10. 日历视图的XML属性