View的工作原理_View的工作流程

View的工作流程:

主要是指:measure,layout,draw这3大流程,measure确定View的测量宽高,layout确定View的最终宽高和4个顶点的位置,而draw则是把View绘制在屏幕上

1,measure过程
measure过程要分 情况来看,如果只是一个原始的View,通过measure方法就完成它的测量,如果是一个ViewGroup,除了完成自己的测量之外还要遍历去调用所有的子元素的measure方法,各个子元素在递归去执行这个流程,下面针对这2种情况分别讨论.

View的measure过程:
View的measure方法是final修饰的方法,子类不能重写,在View的measure方法中会调用onMeasure方法

源码View#measure

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  ...代码省略
   int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
      if (cacheIndex < 0 || sIgnoreMeasureCache) {
           // measure ourselves, this should set the measured dimension flag back
           onMeasure(widthMeasureSpec, heightMeasureSpec);
           mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
       }
  ... 代码省略        
}

源码View#onMeasure

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

setMeasuredDimension()方法会设置View宽高的测量值,因此我们只需要看getDefaultSize()方法

源码View#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;
    }

我们只用考虑AT_MOST和EXACTLY情况,specSize就是测量后的大小,View最终的大小是在layout阶段确定的.getDefaultSize()方法的第一个参数size是由getSuggestedMinimumWidth()这个方法返回的,我们看一下这个方法

源码View#getSuggestedMinimumWidth

protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

如果view没有设置背景,那么view的宽度为mMinWidth,而mMinWidth对应android:minWidth这个属性所指定的值,如果这个属性不指定默认值为0, 如果有设置背景,view取最大值, mBackground.getMinimumWidth()指的是什么意思呢?我们看一下Drawable
的getMinimumWidth()方法

源码Drawable#getMinimumWidth

public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

getIntrinsicWidth()返回的是Drawable的原始宽度,前提是这个Drawable有原始宽度,否则返回0, ShapeDrawable无原始宽高
BitmapDrawable有原始宽高(图片的尺寸)

2 ViewGroup的measure过程:
对于ViewGroup来说,除了完成自己的measure过程还要遍历去调用所有子元素的measure方法,各个子元素再递归去执行这个过程.

a.测量子元素:它提供了一个叫measureChildren的方法去测量子孩子

源码ViewGroup#measureChildren

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:Children复数,指测量多个孩子
measureChild:Child 单数,指测量当前这一个孩子
通过遍历只要孩子的可见性不是GONE,就调用measureChild去测量

源码ViewGroup#measureChild

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()方法就是取出子元素的getLayoutParams,然后通过getChildMeasureSpec()来创建子元素的MeasureSpec,接着把MeasureSpec直接传递给View的measure()方法

b.测量自己:
ViewGroup是一个抽象类,它并没有定义其测量的具体过程,它测量过程的onMeasure方法需要各个子类去具体实现(比如LineaLayout 和RelativeLayout 这两者具有截然不同的布局特性,ViewGroup无法做到统一),具体可以查看各个子类实现的onMeasure方法

2.Layout过程
Layout的作用是ViewGroup用来确定子元素的位置,当ViewGroup的位置被确定后,它在onLayout中会遍历所有字元素,并且调用子元素的layout方法, layout方法是确定当前View的位置,而onLayout方法是确定它所有子view的位置,我们看一下View的layout方法

源码View#layout

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

            if (shouldDrawRoundScrollbar()) {
                if(mRoundScrollbarRenderer == null) {
                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
                }
            } else {
                mRoundScrollbarRenderer = null;
            }

            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);
                }
            }
        }
      ...代码省略
    }

layout的大致流程如下:首先通过setFrame()方法来设定View的4个顶点的位置,4个顶点一旦确定,那么View在父容器中的位置也就确定了,接着调用onLayout方法去确定这个View的子元素的位置,然后判断布局的监听是否为null,不为空就会回调它的onLayoutChange方法,onLayout的具体实现同样和子元素具体的布局有关,所以View的onLayout是一个空实现,要继承View的控件 自己去实现 例如TextView

源码View#onLayout

//空实现,要继承View的控件 自己去实现 例如TextView自己去实现
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

ViewGroup的layout: ViewGroup也没有真正实现onLayout方法,需要继承ViewGroup的控件自己实现,具体可查看LinearLayout等子控件的onLayout方法

源码LinearLayout#onLayout

 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mOrientation == VERTICAL) {
            layoutVertical(l, t, r, b);
        } else {
            layoutHorizontal(l, t, r, b);
        }
    }

3.draw过程
draw的过程分为如下几步:

1,绘制背景 backgroud.draw(canvas)
2,绘制自己(onDraw)
3,绘制孩子(dispatchDraw)
4,绘制装饰(onDrawScrollBars)

源码View#draw

 @CallSuper
    public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading
         *      3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        int saveCount;

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

            drawAutofilledHighlight(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);

            // Step 7, draw the default focus highlight
            drawDefaultFocusHighlight(canvas);

            if (debugDraw()) {
                debugDrawFocus(canvas);
            }

            // we're done...
            return;
        }
    ...代码省略    
}

View绘制过程的传递是通过dispatchDraw来实现的,dispatchDraw会遍历调用所有的子孩子的draw方法,子孩子的draw又会调用dispatchDraw来分发,如此,draw事件就一层层的传递下去了

好啦,到这里可以收工洛,来跟辣条犒劳一下自己~嘻嘻

你可能感兴趣的:(Android基础总结)