View加载详解(二)

来源:互联网 发布:怎么下架淘宝宝贝 编辑:程序博客网 时间:2024/06/08 16:10

上篇我们讲到了ViewRootImpl的performTraversals方法performMeasure测量之前要通过getRootMeasureSpec方法获得顶层视图DecorView的测量规格,跟踪代码进入getRootMeasureSpec()

/**     * Figures out the measure spec for the root view in a window based on it's     * layout params.     *     * @param windowSize     *            The available width or height of the window     *     * @param rootDimension     *            The layout params for one dimension (width or height) of the     *            window.     *     * @return The measure spec to use to measure the root view.     */    private static int getRootMeasureSpec(int windowSize, int rootDimension) {        int measureSpec;        switch (rootDimension) {        //匹配父容器时,测量模式为MeasureSpec.EXACTLY,测量大小直接为屏幕的大小,也就是充满真个屏幕        case ViewGroup.LayoutParams.MATCH_PARENT:            // Window can't resize. Force root view to be windowSize.            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);            break;        //包裹内容时,测量模式为MeasureSpec.AT_MOST,测量大小直接为屏幕大小,也就是充满真个屏幕        case ViewGroup.LayoutParams.WRAP_CONTENT:            // Window can resize. Set max size for root view.            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);            break;        //其他情况时,测量模式为MeasureSpec.EXACTLY,测量大小为DecorView顶层视图布局设置的大小。        default:            // Window wants to be an exact size. Force root view to be that size.            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);            break;        }        return measureSpec;    }

分析:该方法主要作用是在整个窗口的基础上计算出root view(顶层视图DecorView)的测量规格,该方法的两个参数分别表示:
windowSize:当前手机窗口的有效宽和高,一般都是除了通知栏的屏幕宽和高
rootDimension 根布局DecorView请求的宽和高,由前面的博客我们知道是MATCH_PARENT
由 《从setContentView方法分析Android加载布局流程》可知,我们的DecorView根布局宽和高都是MATCH_PARENT,因此DecorView根布局的测量模式就是MeasureSpec.EXACTLY,测量大小一般都是整个屏幕大小,所以一般我们的Activity
窗口都是全屏的。因此上面代码走第一个分支,通过调用MeasureSpec.makeMeasureSpec方法将
DecorView的测量模式和测量大小封装成DecorView的测量规格。
由于performMeasure()方法调用了 View中measure()方法俩进行测量,并且DecorView(继承自FrameLayout)的父类是ViewGroup,祖父类是View。因此我们从View的成员函数measure开始分析整个测量过程。
这里写图片描述

虽然说上面的可能有点枯燥,大家感觉没有卵用,但下面重头戏开始了

int mOldWidthMeasureSpec = Integer.MIN_VALUE;    int mOldHeightMeasureSpec = Integer.MIN_VALUE; public final void measure(int widthMeasureSpec, int heightMeasureSpec) {        ..................        //如果上一次的测量规格和这次不一样,则条件满足,重新测量视图View的大小        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||                widthMeasureSpec != mOldWidthMeasureSpec ||                heightMeasureSpec != mOldHeightMeasureSpec) {            // first clears the measured dimension flag            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;            resolveRtlPropertiesIfNeeded();            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -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;            } else {                long value = mMeasureCache.valueAt(cacheIndex);                // Casting a long to int drops the high 32 bits, no mask needed                setMeasuredDimensionRaw((int) (value >> 32), (int) value);                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;            }            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;        }        mOldWidthMeasureSpec = widthMeasureSpec;        mOldHeightMeasureSpec = heightMeasureSpec;    }
 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||                widthMeasureSpec != mOldWidthMeasureSpec ||                heightMeasureSpec != mOldHeightMeasureSpec) {

判断当前视图View是否需要重新测量,当上一次视图View测量的规格和本次视图View测量规格不一样时,就说明视图View的大小有改变,因此需要重新测量
然后调用了onMeasure方法进行测量,说明View主要的测量逻辑是在该方法中实现

/**     * <p>     * Measure the view and its content to determine the measured width and the     * measured height. This method is invoked by {@link #measure(int, int)} and     * should be overriden by subclasses to provide accurate and efficient     * measurement of their contents.     * </p>     *     * <p>     * <strong>CONTRACT:</strong> When overriding this method, you     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the     * measured width and height of this view. Failure to do so will trigger an     * <code>IllegalStateException</code>, thrown by     * {@link #measure(int, int)}. Calling the superclass'     * {@link #onMeasure(int, int)} is a valid use.     * </p>     *     * <p>     * The base class implementation of measure defaults to the background size,     * unless a larger size is allowed by the MeasureSpec. Subclasses should     * override {@link #onMeasure(int, int)} to provide better measurements of     * their content.     * </p>     *     * <p>     * If this method is overridden, it is the subclass's responsibility to make     * sure the measured height and width are at least the view's minimum height     * and width ({@link #getSuggestedMinimumHeight()} and     * {@link #getSuggestedMinimumWidth()}).     * </p>     *     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.     *                         The requirements are encoded with     *                         {@link android.view.View.MeasureSpec}.     * @param heightMeasureSpec vertical space requirements as imposed by the parent.     *                         The requirements are encoded with     *                         {@link android.view.View.MeasureSpec}.     *     * @see #getMeasuredWidth()     * @see #getMeasuredHeight()     * @see #setMeasuredDimension(int, int)     * @see #getSuggestedMinimumHeight()     * @see #getSuggestedMinimumWidth()     * @see android.view.View.MeasureSpec#getMode(int)     * @see android.view.View.MeasureSpec#getSize(int)     */    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));    }

该方法的实现也很简单,直接调用setMeasuredDimension方法完成视图View的测量。我们知道,Android中所有的视图组件都是继承自View实现的。因此该方法提供了一个默认测量视图View大小的实现。言外之意,如果你不想你自己的View使用默认实现来测量View的宽高的话,你可以在子类中重写onMeasure方法来自定义测量方法。我们先来看看默认测量宽高的实现。跟踪代码进入getDefaultSize方法

 /**     * Utility to return a default size. Uses the supplied size if the     * MeasureSpec imposed no constraints. Will get larger if allowed     * by the MeasureSpec.     *     * @param size Default size for this view     * @param measureSpec Constraints imposed by the parent     * @return The size this view should be.     */    public static int getDefaultSize(int size, int measureSpec) {        int result = size;        //获得测量模式        int specMode = MeasureSpec.getMode(measureSpec);        //获得父亲容器留给子视图View的大小        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;    }

分析:该方法的作用是根据View布局设置的宽高和父View传递的测量规格重新计算View的测量宽高。由此可以知道,我们布局的子View最终的大小是由布局大小和父容器的测量规格共同决定的。如果自定义View你没有重写onMeasure使用系统默认方法的话,测量模式MeasureSpec.AT_MOST和MeasureSpec.EXACTLY下的测量大小是一样的。我们来总结一下测量模式的种类:
MeasureSpec.EXACTLY:确定模式,父容器希望子视图View的大小是固定,也就是specSize大小。
MeasureSpec.AT_MOST:最大模式,父容器希望子视图View的大小不超过父容器希望的大小,也就是不超过specSize大小。
MeasureSpec.UNSPECIFIED: 不确定模式,子视图View请求多大就是多大,父容器不限制其大小范围,也就是size大小。
从上面代码可以看出,当测量模式是MeasureSpec.UNSPECIFIED时,View的测量值为size,当测量模式为MeasureSpec.AT_MOST或者case MeasureSpec.EXACTLY时,View的测量值为specSize。我们知道,specSize是由父容器决定,那么size是怎么计算出来的呢?getDefaultSize方法的第一个参数是调用getSuggestedMinimumWidth方法获得。进入getSuggestedMinimumWidth方法看看实现:

/**     * Returns the suggested minimum width that the view should use. This     * returns the maximum of the view's minimum width)     * and the background's minimum width     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).     * <p>     * When being used in {@link #onMeasure(int, int)}, the caller should still     * ensure the returned width is within the requirements of the parent.     *     * @return The suggested minimum width of the view.     */    protected int getSuggestedMinimumWidth() {        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());    }

原来size大小是获取View属性当中的最小值,也就是 android:minWidth和 android:minHeight的值,前提是View没有设置背景属性。否则就在最小值和背景的最小值中间取最大值。sizeSpec大小是有父容器决定的,我们知道父容器DecorView的测量模式是MeasureSpec.EXACTLY,测量大小sizeSpec是整个屏幕的大小。而DecorView是继承自FrameLayout的,那么我们来看看FrameLayout类中的onMeasure方法的实现

@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int count = getChildCount();        ..............        int maxHeight = 0;        int maxWidth = 0;        int childState = 0;        for (int i = 0; i < count; i++) {            final View child = getChildAt(i);            if (mMeasureAllChildren || child.getVisibility() != GONE) {                //测量FrameLayout下每个子视图View的宽和高                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);                final LayoutParams lp = (LayoutParams) child.getLayoutParams();                maxWidth = Math.max(maxWidth,                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);                maxHeight = Math.max(maxHeight,                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);                childState = combineMeasuredStates(childState, child.getMeasuredState());                if (measureMatchParentChildren) {                    if (lp.width == LayoutParams.MATCH_PARENT ||                            lp.height == LayoutParams.MATCH_PARENT) {                        mMatchParentChildren.add(child);                    }                }            }        }        // Account for padding too        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();        // Check against our minimum height and width        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());        // Check against our foreground's minimum height and width        final Drawable drawable = getForeground();        if (drawable != null) {            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());        }        //设置当前FrameLayout测量结果,此方法的调用表示当前View测量的结束。        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),                resolveSizeAndState(maxHeight, heightMeasureSpec,                        childState << MEASURED_HEIGHT_STATE_SHIFT));}

分析:由以上代码发现,ViewGroup测量结果都是带边距的,前面部分就是遍历测量FrameLayout下子视图View的大小了。最后调用setMeasuredDimension方法设置当前View的测量结果,此方法的调用表示当前View测量结束。那么我们来分析下代码第12行measureChildWithMargins方法测FrameLayout下的子视图View的大小,跟踪源码:
由于FrameLayout父类是ViewGroup,measureChildWithMargins方法在ViewGroup下

/**     * Ask one of the children of this view to measure itself, taking into     * account both the MeasureSpec requirements for this view and its padding     * and margins. The child must have MarginLayoutParams The heavy lifting is     * done in getChildMeasureSpec.     *     * @param child The child to measure     * @param parentWidthMeasureSpec The width requirements for this view     * @param widthUsed Extra space that has been used up by the parent     *        horizontally (possibly by other children of the parent)     * @param parentHeightMeasureSpec The height requirements for this view     * @param heightUsed Extra space that has been used up by the parent     *        vertically (possibly by other children of the parent)     */    protected void measureChildWithMargins(View child,            int parentWidthMeasureSpec, int widthUsed,            int parentHeightMeasureSpec, int heightUsed) {        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin                        + widthUsed, lp.width);        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin                        + heightUsed, lp.height);        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);    }

该方法中调用getChildMeasureSpec方法来获得ViewGroup下的子视图View的测量规格。然后将测量规格最为参数传递给View的measure方法,最终完成所有子视图View的测量。来看看这里是怎么获得子视图View的测量规格的,进入getChildMeasureSpec方法:

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {        int specMode = MeasureSpec.getMode(spec);        int specSize = MeasureSpec.getSize(spec);        int size = Math.max(0, specSize - padding);        int resultSize = 0;        int resultMode = 0;        switch (specMode) {        // Parent has imposed an exact size on us        case MeasureSpec.EXACTLY:            if (childDimension >= 0) {                resultSize = childDimension;                resultMode = MeasureSpec.EXACTLY;            } else if (childDimension == LayoutParams.MATCH_PARENT) {                // Child wants to be our size. So be it.                resultSize = size;                resultMode = MeasureSpec.EXACTLY;            } else if (childDimension == LayoutParams.WRAP_CONTENT) {                // Child wants to determine its own size. It can't be                // bigger than us.                resultSize = size;                resultMode = MeasureSpec.AT_MOST;            }            break;       ...........        }        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);    }

分析:节我们知道根布局DecorView的测量规格中的测量模式是MeasureSpec.EXACTLY,测量大小是整个窗口大小。因此上面代码分支走MeasureSpec.EXACTLY。子视图View的测量规格由其宽和高参数决定。
当DecorView根布局的子视图View宽高为一个确定值childDimension时,该View的测量模式为MeasureSpec.EXACTLY,测量大小就是childDimension。
当子视图View宽高为MATCH_PARENT时,该View的测量模式为MeasureSpec.EXACTLY,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。
当子视图View宽高为WRAP_CONTENT时,该View的测量模式为MeasureSpec.AT_MOST,测量大小是父容器DecorView规定的大小,为整个屏幕大小MATCH_PARENT。
这里我们来验证一下以上的结论,目的是进一步理解 View的几种测量模式和View的测量规格。

<com.xjp.layoutdemo.MyView    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="Button"    android:gravity="start"/>

这个布局很简单,直接将自定义的MyView作为Activity的内容布局。
2.自定义MyView代码如下:

public class MyView extends View {    private static final String TAG = "MyCustomView";    private String titleText = "Hello world";    private int titleColor = Color.BLACK;    private int titleBackgroundColor = Color.RED;    private int titleSize = 16;    private Paint mPaint;    private Rect mBound;    public MyView(Context context) {        this(context, null);    }    public MyView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int specMode = MeasureSpec.getMode(widthMeasureSpec);        int specSize = MeasureSpec.getSize(widthMeasureSpec);        switch (specMode) {            case MeasureSpec.UNSPECIFIED:                Log.e(TAG, "UNSPECIFIED.....");                break;            case MeasureSpec.AT_MOST:                Log.e(TAG, "AT_MOST.....");                break;            case MeasureSpec.EXACTLY:                Log.e(TAG, "EXACTLY.....");                break;        }        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    /**     * 初始化     */    private void init() {        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);        mPaint.setTextSize(titleSize);        /**         * 得到自定义View的titleText内容的宽和高         */        mBound = new Rect();        mPaint.getTextBounds(titleText, 0, titleText.length(), mBound);    }    @Override    protected void onDraw(Canvas canvas) {        mPaint.setColor(titleBackgroundColor);        canvas.drawCircle(getWidth() / 2f, getWidth() / 2f, getWidth() / 2f, mPaint);        mPaint.setColor(titleColor);        canvas.drawText(titleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);    }}

这里写图片描述
自定义的MyView也很简单,仅仅重写了onDraw方法,onMeasure方法调用父类方法。代码运行之后你会发现,

1.布局中设置的MyView大小是wrap_content包裹内容的,但是View视图却充满整个屏幕。看打印发现当前的测量模式是MeasureSpec.AT_MOST。
2.当MyView大小是match_parent填满父容器时,View视图也是充满整个屏幕,看打印发现测量模式是MeasureSpec.EXACTLY。
3.当MyView大小是固定值,比如是1200dp和1200dp时,View视图是超出整个屏幕的。

原因是此处的Activity内容布局的父容器也是一个id为content的FrameLayout布局。这里就不解释以上三种情况的原因了,前面的很详细了。
至此,整个View树型结构的布局测量流程可以归纳如下:
这里写图片描述
measure总结

1、View的measure方法是final类型的,子类不可以重写,子类可以通过重写onMeasure方法来测量自己的大小,当然也可以不重写onMeasure方法使用系统默认测量大小。
2、View测量结束的标志是调用了View类中的setMeasuredDimension成员方法,言外之意是,如果你需要在自定义的View中重写onMeasure方法,在你测量结束之前你必须调用setMeasuredDimension方法测量才有效。
3、在Activity生命周期onCreate和onResume方法中调用View.getWidth()和View.getMeasuredHeight()返回值为0的,是因为当前View的测量还没有开始,这里关系到Activity启动过程,文章开头说了当ActivityThread类中的performResumeActivity方法执行之后才将DecorView添加到PhoneWindow窗口上,开始测量。在Activity生命周期onCreate在中performResumeActivity还为执行,因此调用View.getMeasuredHeight()返回值为0。

4、子视图View的大小是由父容器View和子视图View布局共同决定的。
布局Layout
View视图绘制流程中的布局layout是由ViewRootImpl中的performLayout成员方法开始的,看源码:

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,            int desiredWindowHeight) {        //标记当前开始布局        mInLayout = true;        //mView就是DecorView        final View host = mView;        //DecorView请求布局        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());        //标记布局结束        mInLayout = false;}

DecorView的四个位置左=0,顶=0,右=屏幕宽,底=屏幕宽,说明DecorView布局的位置是从屏幕最左最顶端开始布局,到屏幕最低最右结束。因此DecorView根布局是充满整个屏幕的。

该方法主要调用了View类的layout方法,跟踪代码进入View类的layout方法瞧瞧吧

/**     * Assign a size and position to a view and all of its     * descendants     *     * <p>This is the second phase of the layout mechanism.     * (The first is measuring). In this phase, each parent calls     * layout on all of its children to position them.     * This is typically done using the child measurements     * that were stored in the measure pass().</p>     *     * <p>Derived classes should not override this method.     * Derived classes with children should override     * onLayout. In that method, they should     * call layout on each of their children.</p>     *     * @param l Left position, relative to parent     * @param t Top position, relative to parent     * @param r Right position, relative to parent     * @param b Bottom position, relative to parent     */    @SuppressWarnings({"unchecked"})    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;        }        //保存上一次View的四个位置        int oldL = mLeft;        int oldT = mTop;        int oldB = mBottom;        int oldR = mRight;        //设置当前视图View的左,顶,右,底的位置,并且判断布局是否有改变        boolean changed = isLayoutModeOptical(mParent) ?                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);        //如果布局有改变,条件成立,则视图View重新布局            if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {            //调用onLayout,将具体布局逻辑留给子类实现            onLayout(changed, l, t, r, b);            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;            ListenerInfo li = mListenerInfo;            if (li != null && li.mOnLayoutChangeListeners != null) {                ArrayList<OnLayoutChangeListener> listenersCopy =                        (ArrayList<OnLayoutChangeListener>)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;    }

前面部分保存布局的四个位置,用于布局变化的监听事件,如果用户设置了布局变化的监听事件,则代码后面就会执行设置监听事件。

后面设置当前View的布局位置,也就是当调用了setFrame(l, t, r, b)方法之后,当前View布局基本完成,这里来分析一下setFrame是怎么设置当前View的布局位置的。

/**     * Assign a size and position to this view.     *     * This is called from layout.     *     * @param left Left position, relative to parent     * @param top Top position, relative to parent     * @param right Right position, relative to parent     * @param bottom Bottom position, relative to parent     * @return true if the new size and position are different than the     *         previous ones     * {@hide}     */    protected boolean setFrame(int left, int top, int right, int bottom) {        boolean changed = false;        //当上,下,左,右四个位置有一个和上次的值不一样都会重新布局        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {            changed = true;            // Remember our drawn bit            int drawn = mPrivateFlags & PFLAG_DRAWN;            //得到本次和上次的宽和高            int oldWidth = mRight - mLeft;            int oldHeight = mBottom - mTop;            int newWidth = right - left;            int newHeight = bottom - top;            //判断本次View的宽高和上次View的宽高是否相等            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);            // Invalidate our old position            //清楚上次布局的位置            invalidate(sizeChanged);            //保存当前View的最新位置            mLeft = left;            mTop = top;            mRight = right;            mBottom = bottom;            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);            mPrivateFlags |= PFLAG_HAS_BOUNDS;            //如果当前View的尺寸有所变化            if (sizeChanged) {                sizeChange(newWidth, newHeight, oldWidth, oldHeight);            }            ...............        return changed;    }

分析:
如果当前View视图的最新位置和上一次不一样时,则View会重新布局。

保存当前View的最新位置,到此当前View的布局基本结束。从这里我们可以看到,四个全局变量 mLeft,mTop,mRight,mBottom在此刻赋值,联想我们平时使用的View.getWidth()方法获得View的宽高,你可以发现,其实View.getWidth()方法的实现如下:

public final int getWidth() {        return mRight - mLeft;    } public final int getHeight() {        return mBottom - mTop;    }

也就是说,以上两个方法是获得View布局时候的宽高,因此,我们只有在View 布局完之后调用getWidth才能真正获取到大于0的值。

细心的你会发现,前面调用了setFrame方法,也就是当前View的布局结束了,那么View中的onLayout方法又是干嘛的呢?进入onLayout方法:

/**     * Called from layout when this view should     * assign a size and position to each of its children.     *     * Derived classes with children should override     * this method and call layout on each of     * their children.     * @param changed This is a new size or position for this view     * @param left Left position, relative to parent     * @param top Top position, relative to parent     * @param right Right position, relative to parent     * @param bottom Bottom position, relative to parent     */    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {    }

分析:原来这是一个空方法,既然是空方法,那么该方法的实现应该在子类中。前面分析过,DecorView是继承自FrameLayout的,那么进入FarmeLayout类中看看 onLayout方法的实现吧:

* {@inheritDoc}     */    @Override    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {        layoutChildren(left, top, right, bottom, false /* no force left gravity */);    }    void layoutChildren(int left, int top, int right, int bottom,                                  boolean forceLeftGravity) {        final int count = getChildCount();        final int parentLeft = getPaddingLeftWithForeground();        final int parentRight = right - left - getPaddingRightWithForeground();        final int parentTop = getPaddingTopWithForeground();        final int parentBottom = bottom - top - getPaddingBottomWithForeground();        mForegroundBoundsChanged = true;        //遍历当前FrameLayout下的子View        for (int i = 0; i < count; i++) {            final View child = getChildAt(i);            //当子视图View可见度设置为GONE时,不进行当前子视图View的布局,这就是为什么当你布局中使用Visibility=GONE时,该view是不占据空间的。            if (child.getVisibility() != GONE) {                final LayoutParams lp = (LayoutParams) child.getLayoutParams();                //获得子视图View的宽高                final int width = child.getMeasuredWidth();                final int height = child.getMeasuredHeight();                int childLeft;                int childTop;                int gravity = lp.gravity;                if (gravity == -1) {                    gravity = DEFAULT_CHILD_GRAVITY;                }                final int layoutDirection = getLayoutDirection();                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;                //一下代码获得子视图View的四个位置,用于子视图View布局。                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {                    case Gravity.CENTER_HORIZONTAL:                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +                        lp.leftMargin - lp.rightMargin;                        break;                    case Gravity.RIGHT:                        if (!forceLeftGravity) {                            childLeft = parentRight - width - lp.rightMargin;                            break;                        }                    case Gravity.LEFT:                    default:                        childLeft = parentLeft + lp.leftMargin;                }                switch (verticalGravity) {                    case Gravity.TOP:                        childTop = parentTop + lp.topMargin;                        break;                    case Gravity.CENTER_VERTICAL:                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +                        lp.topMargin - lp.bottomMargin;                        break;                    case Gravity.BOTTOM:                        childTop = parentBottom - height - lp.bottomMargin;                        break;                    default:                        childTop = parentTop + lp.topMargin;                }                //子视图布局                child.layout(childLeft, childTop, childLeft + width, childTop + height);            }        }    }

分析:在FrameLayout中的onLayout方法中仅仅是调用了layoutChildren方法,从该方法名称我们不难看出,原来该方法的作用是

给子视图View进行布局的。也就是说FrameLayout布局其实在View类中的layout方法中已经实现,布局的逻辑实现是在父视图中

实现的,不像View视图的measure测量,通过子类实现onMeasure方法来实现测量逻辑。

1.,遍历获得FrameLayout的子视图View的四个位置,然后调用child.layout对子视图View进行布局操作。

2.,对每个子视图View的可见度进行了判断,如果当前子视图View可见度类型为GONE,则当前子视图View不进行布局,这也就是为什么可见度GONE类型时是不占据屏幕空间的,而其他两种VISIBLE和INVISIBLE是占据屏幕空间的。
由于FrameLayout类是继承自ViewGroup类的,那么我们进入ViewGroup类去窥探一下onLayout方法具体做了什么?

/**     * {@inheritDoc}     */    @Override    protected abstract void onLayout(boolean changed,            int l, int t, int r, int b);```![这里写图片描述](http://img.blog.csdn.net/20160406195336062)layout布局总结1.视图View的布局逻辑是由父View,也就是ViewGroup容器布局来实现的。因此,我们如果自定义View一般都无需重写onMeasure方法,但是如果自定义一个ViewGroup容器的话,就必须实现onLayout方法,因为该方法在ViewGroup是抽象的,所有ViewGroup的所有子类必须实现onLayout方法。2.当我们的视图View在布局中使用 android:visibility=”gone” 属性时,是不占据屏幕空间的,因为在布局时ViewGroup会遍历每个子视图View,判断当前子视图View是否设置了 Visibility==GONE,如果设置了,当前子视图View就会添加到父容器上,因此也就不占据屏幕空间。3.必须在View布局完之后调用getHeight()和getWidth()方法获取到的View的宽高才大于0。具体可View的绘制DrawView视图绘制流程中的最后一步绘制draw是由ViewRootImpl中的performDraw成员方法开始的,跟踪代码,最后会在ViewRootImpl类中的drawSoftware方法绘制View:<div class="se-preview-section-delimiter"></div>

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {

    // Draw with software renderer.    final Canvas canvas;    try {        //从surface对象中获得canvas变量        canvas = mSurface.lockCanvas(dirty);        // If this bitmap's format includes an alpha channel, we        // need to clear it before drawing so that the child will        // properly re-composite its drawing on a transparent        // background. This automatically respects the clip/dirty region        // or        // If we are applying an offset, we need to clear the area        // where the offset doesn't appear to avoid having garbage        // left in the blank areas.        if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {            canvas.drawColor(0, PorterDuff.Mode.CLEAR);        }       ......................        try {            //调整画布的位置            canvas.translate(-xoff, -yoff);            if (mTranslator != null) {                mTranslator.translateCanvas(canvas);            }            canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);            attachInfo.mSetIgnoreDirtyState = false;            //调用View类中的成员方法draw开始绘制View视图            mView.draw(canvas);        }     return true;}

“`

 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,            boolean scalingRequired, Rect dirty) {        // Draw with software renderer.        final Canvas canvas;        try {            //从surface对象中获得canvas变量            canvas = mSurface.lockCanvas(dirty);            // If this bitmap's format includes an alpha channel, we            // need to clear it before drawing so that the child will            // properly re-composite its drawing on a transparent            // background. This automatically respects the clip/dirty region            // or            // If we are applying an offset, we need to clear the area            // where the offset doesn't appear to avoid having garbage            // left in the blank areas.            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {                canvas.drawColor(0, PorterDuff.Mode.CLEAR);            }           ......................            try {                //调整画布的位置                canvas.translate(-xoff, -yoff);                if (mTranslator != null) {                    mTranslator.translateCanvas(canvas);                }                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);                attachInfo.mSetIgnoreDirtyState = false;                //调用View类中的成员方法draw开始绘制View视图                mView.draw(canvas);            }         return true;    }

分析:代码第8行,从mSurface对象中获得canvas画布,然后将变量canvas变量作为参数传递给第33行代码中的draw方法。由此

可知,我们的视图View最终是绘制到Surface中去的,关于Surface相关的知识,可以参考这篇大神的博客:

Android应用程序窗口(Activity)的绘图表面(Surface)的创建过程分析

跟踪代码,进入View的draw方法分析源码:

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);            // Step 6, draw decorations (scrollbars)            onDrawScrollBars(canvas);            if (mOverlay != null && !mOverlay.isEmpty()) {                mOverlay.getOverlayView().dispatchDraw(canvas);            }            // we're done...            return;        }        /*         * Here we do the full fledged routine...         * (this is an uncommon case where speed matters less,         * this is why we repeat some of the tests that have been         * done above)         */        boolean drawTop = false;        boolean drawBottom = false;        boolean drawLeft = false;        boolean drawRight = false;        float topFadeStrength = 0.0f;        float bottomFadeStrength = 0.0f;        float leftFadeStrength = 0.0f;        float rightFadeStrength = 0.0f;        // Step 2, save the canvas' layers        int paddingLeft = mPaddingLeft;        final boolean offsetRequired = isPaddingOffsetRequired();        if (offsetRequired) {            paddingLeft += getLeftPaddingOffset();        }        int left = mScrollX + paddingLeft;        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;        int top = mScrollY + getFadeTop(offsetRequired);        int bottom = top + getFadeHeight(offsetRequired);        if (offsetRequired) {            right += getRightPaddingOffset();            bottom += getBottomPaddingOffset();        }        final ScrollabilityCache scrollabilityCache = mScrollCache;        final float fadeHeight = scrollabilityCache.fadingEdgeLength;        int length = (int) fadeHeight;        // clip the fade length if top and bottom fades overlap        // overlapping fades produce odd-looking artifacts        if (verticalEdges && (top + length > bottom - length)) {            length = (bottom - top) / 2;        }        // also clip horizontal fades if necessary        if (horizontalEdges && (left + length > right - length)) {            length = (right - left) / 2;        }        if (verticalEdges) {            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));            drawTop = topFadeStrength * fadeHeight > 1.0f;            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;        }        if (horizontalEdges) {            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));            drawLeft = leftFadeStrength * fadeHeight > 1.0f;            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));            drawRight = rightFadeStrength * fadeHeight > 1.0f;        }        saveCount = canvas.getSaveCount();        int solidColor = getSolidColor();        if (solidColor == 0) {            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;            if (drawTop) {                canvas.saveLayer(left, top, right, top + length, null, flags);            }            if (drawBottom) {                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);            }            if (drawLeft) {                canvas.saveLayer(left, top, left + length, bottom, null, flags);            }            if (drawRight) {                canvas.saveLayer(right - length, top, right, bottom, null, flags);            }        } else {            scrollabilityCache.setFadeColor(solidColor);        }        // Step 3, draw the content        if (!dirtyOpaque) onDraw(canvas);        // Step 4, draw the children        dispatchDraw(canvas);        // Step 5, draw the fade effect and restore layers        final Paint p = scrollabilityCache.paint;        final Matrix matrix = scrollabilityCache.matrix;        final Shader fade = scrollabilityCache.shader;        if (drawTop) {            matrix.setScale(1, fadeHeight * topFadeStrength);            matrix.postTranslate(left, top);            fade.setLocalMatrix(matrix);            p.setShader(fade);            canvas.drawRect(left, top, right, top + length, p);        }        if (drawBottom) {            matrix.setScale(1, fadeHeight * bottomFadeStrength);            matrix.postRotate(180);            matrix.postTranslate(left, bottom);            fade.setLocalMatrix(matrix);            p.setShader(fade);            canvas.drawRect(left, bottom - length, right, bottom, p);        }        if (drawLeft) {            matrix.setScale(1, fadeHeight * leftFadeStrength);            matrix.postRotate(-90);            matrix.postTranslate(left, top);            fade.setLocalMatrix(matrix);            p.setShader(fade);            canvas.drawRect(left, top, left + length, bottom, p);        }        if (drawRight) {            matrix.setScale(1, fadeHeight * rightFadeStrength);            matrix.postRotate(90);            matrix.postTranslate(right, top);            fade.setLocalMatrix(matrix);            p.setShader(fade);            canvas.drawRect(right - length, top, right, bottom, p);        }        canvas.restoreToCount(saveCount);        // Step 6, draw decorations (scrollbars)        onDrawScrollBars(canvas);        if (mOverlay != null && !mOverlay.isEmpty()) {            mOverlay.getOverlayView().dispatchDraw(canvas);        }    }

这里写图片描述
绘制当前视图的背景。

保存当前画布的堆栈状态,并且在在当前画布上创建额外的图层,以便接下来可以用来绘制当前视图在滑动时的边框渐变效果。

绘制当前视图的内容。

绘制当前视图的子视图的内容。

绘制当前视图在滑动时的边框渐变效果。

绘制当前视图的滚动条。
由于篇幅的原因绘制放在下个章节讲谢谢

0 0