FrameLayout绘制 源码详解

一直以来都想搞清楚Android中View控件的绘制过程,怎奈自己以前能力不济再加上懒惰,自制力欠缺导致这件事情一直处于半将半就的状态。模模糊糊的了解到绘制分为measure测量、layout布局、draw绘制三步,但是针对其中涉及到的一些点一直有些恍惚,像方法measure()和onMeasure()、layout()和onLayout()、draw()和onDraw()相互之间的关系,它们各自的职责以及相互是如何配合的。其中尤以onMeasure在父子之间的调用顺序最让自己疑惑,今天通过分析FragmentLayout的绘制过程,让我们将这些疑问统统解决掉。也许你会问,为什么是FrameLayout?因为我觉得他最简单,是个软柿子,要怎滴!哈哈,言归正传!

这里有一点需要强调一下:分析的源码是Android 6.0的(API 23),如果跟您手边的源码有出入,大概是版本不同导致的!毕竟,Google在一直重构、优化Android的SDK嘛!

首先看一下FrameLayout的继承关系

FrameLayout –> ViewGroup –> View

onMeasure过程分析

在分析FrameLayout的onMeasure之前,我们先陈述一些基础知识点:我们知道跟一个控件尺寸相关的属性有(这里一height举例)layout_height、maxHeight、minHeight等,在这里我们都知道layout_height有三种可能的取值:MATCH_PARENT=-1、WRAP_CONTENT=-2和具体的数值,相信具体的含义大家都知道;还有onMeasure的int型参数高2位代表measureMode,低30位代表measureSize,而measureMode有三种可能的取值:MeasureSpec.EXACTLY、MeasureSpec.AT_MOST、MeasureSpec.UNSPECIFIED,MeasureSpec.EXACTLY代表子控件应该严格按照measureSize大小赋值,MeasureSpec.AT_MOST代表子控件最大为measureSize的大小而MeasureSpec.UNSPECIFIED代表不做任何限制。现在看来还一目了然,等到父控件套子控件,子控件再套孙子控件,父、子、孙子的layout_height再赋予不同的值得时候,是父控件先确定measure结果,还是子控件先确定measure结果,父子之间如何协商、onMeasure调用几次、layout_margin、padding、minHeight和maxHeight如何起作用?等等问题袭来,真是一团乱麻,下面从对FrameLayout的解剖中探寻究竟吧!

onMeasure(int widthMeasureSpec, int heightMeasureSpec)源码(==代码的说明在代码的注释中==):

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;//是否需要重新测绘属性为MATCH_PARENT的子控件,在下面会用到
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        //首先,将父控件的padding和子控件的margin考虑在内,先来测绘子控件的大小,measureChildWithMargins函数会在下边展开
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                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());
        }

        //从子控件的最大值(子控件的大小加上padding和foregroundPadding综合考虑的大小),背景的最小值、前景的最小值和控件的最小值属性综合考虑,取得其中的最大值,再考虑到父控件的measureSpec得到父控件也就是FrameLayout的大小。resolveSizeAndState在下边展开
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));


        //如果需要重新测量属性为match_parent的子控件则重新测量
        count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }

ViewGroup.measureChildWithMargins源码

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        //根据父控件的padding和子控件margin以及父控件的measureSpec和子控件的lp.width决定子控件的measureSpec,getChildMeasureSpec会在下边展开
        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);
    }

ViewGroup.getChildMeasureSpec的源码

/**
*这个函数有几个遵从的原则,或许能帮助更好的理解代码:1、如果子控件指定了具体的大小则MeasureSpec的模式为EXACTLY值为指定大小;2、如果子控件的需求跟父控件的需求有冲突则以父控件为准;
*/
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;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } 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;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

View.resolveSizeAndState源码

/**
*还是需求跟供给冲突了,以供给为准(FrameLayout想要的大小跟measureSpec冲突,以measureSpec为准)
*/
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
        final int specMode = MeasureSpec.getMode(measureSpec);
        final int specSize = MeasureSpec.getSize(measureSpec);
        final int result;
        switch (specMode) {
            case MeasureSpec.AT_MOST:
                if (specSize < size) {
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
    }

onLayout过程分析

onMeasure测量出控件自身的大小,而onLayout通过调用子控件的layout决定子控件的位置和大小(这里的大小是控件最终呈现的状态,一般就是控件测量的大小),onLayout的过程跟FrameLayout的gravity和子控件的layout_gravity属性有关,下边看一下FrameLayout的onLayout过程:

onLayout(boolean changed, int left, int top, int right, int bottom源码

/**
*这里需要明确一下坐标系,子控件的所在的坐标系是由父控件确定的。拿这里举例,FrameLayout的onLayout的参数值,是以FrameLayout的父控件左上角为坐标原点的坐标系中的值。而接下调用child.layout确定FrameLayout的子控件的位置和大小的函数中的参数值是以FrameLayout左上角为原点的坐标系中的值
*/
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }

layoutChildren源码

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

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                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();
                //将布局中的start、end转化为left、right
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                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是几大布局中最简单的一个,比较适合入门。通过分析FrameLayout对控件的绘制过程有个大概的了解。其他Layout的measure过程可能更复杂,需要更多的父子控件的协商。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值