深入解析 Android 中 View 的工作原理
ming393177
7年前
<p>Android中的任何一个布局、任何一个控件其实都是直接或间接继承自View实现的,当然也包括我们在平时开发中所写的各种炫酷的自定义控件了,所以学习View的工作原理对于我们来说显得格外重要,本篇博客,我们将一起深入学习Android中View的工作原理。</p> <h2>ViewRoot和DecorView</h2> <p>1.ViewRoot对应于ViewRootImpl类,是连接WindowManager和DecorView的纽带,View的三大流程均是通过ViewRoot来完成的。在ActivityThread中,当Activity对象被创建完毕后,会将DecorView添加到Window中,同时会创建ViewRootImpl对象,并将ViewRootImpl对象和DecorView建立关联。</p> <p>2.View的绘制流程从ViewRoot的performTraversals开始,经过measure、layout和draw三个过程才可以把一个View绘制出来,其中measure用来测量View的宽高,layout用来确定View在父容器中的放置位置,而draw则负责将View绘制到屏幕上。</p> <p>3.performTraversals会依次调用performMeasure、performLayout和performDraw三个方法,这三个方法分别完成顶级View的measure、layout和draw这三大流程。其中performMeasure中会调用measure方法,在measure方法中又会调用onMeasure方法,在onMeasure方法中则会对所有子元素进行measure过程,这样就完成了一次measure过程;子元素会重复父容器的measure过程,如此反复完成了整个View数的遍历。</p> <p style="text-align:center"><img src="https://simg.open-open.com/show/188cbff7ac1167215ad01dde6e64f49c.png"></p> <p>measure过程决定了View的宽/高,完成后可通过getMeasuredWidth/getMeasureHeight方法来获取View测量后的宽/高。Layout过程决定了View的四个顶点的坐标和实际View的宽高,完成后可通过getTop、getBotton、getLeft和getRight拿到View的四个定点坐标。Draw过程决定了View的显示,完成后View的内容才能呈现到屏幕上。</p> <p>DecorView作为顶级View,一般情况下它内部包含了一个竖直方向的LinearLayout,里面分为两个部分(具体情况和Android版本和主题有关),上面是标题栏,下面是内容栏。在Activity通过setContextView所设置的布局文件其实就是被加载到内容栏之中的。</p> <pre> <code class="language-java">//获取内容栏 ViewGroup content = findViewById(R.android.id.content); //获取我们设置的Viewcontext.getChildAt(0); DecorView其实是一个FrameLayout,View层的事件都先经过DecorView,然后才传给我们的View。</code></pre> <p style="text-align:center"><img src="https://simg.open-open.com/show/c445c1ea65eed8f947eb93fd79cc0e9e.png"></p> <h2>MeasureSpec</h2> <p>1.MeasureSpec很大程度上决定一个View的尺寸规格,测量过程中,系统会将View的layoutParams根据父容器所施加的规则转换成对应的MeasureSpec,再根据这个measureSpec来测量出View的宽/高。</p> <p>2.MeasureSpec代表一个32位的int值,高2位为SpecMode,低30位为SpecSize,SpecMode是指测量模式,SpecSize是指在某种测量模式下的规格大小。</p> <p>MpecMode有三类;</p> <p>1.UNSPECIFIED 父容器不对View进行任何限制,要多大给多大,一般用于系统内部</p> <p>2.EXACTLY 父容器检测到View所需要的精确大小,这时候View的最终大小就是SpecSize所指定的值,对应LayoutParams中的match_parent和具体数值这两种模式。</p> <p>3.AT_MOST 父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,不同View实现不同,对应LayoutParams中的wrap_content。</p> <p>当View采用固定宽/高的时候,不管父容器的MeasureSpec的是什么,View的MeasureSpec都是精确模式兵其大小遵循Layoutparams的大小。 当View的宽/高是match_parent时,如果他的父容器的模式是精确模式,那View也是精确模式并且大小是父容器的剩余空间;如果父容器是最大模式,那么View也是最大模式并且起大小不会超过父容器的剩余空间。 当View的宽/高是wrap_content时,不管父容器的模式是精确还是最大化,View的模式总是最大化并且不能超过父容器的剩余空间。</p> <p>对于DecorView,它的MeasureSpec由Window的尺寸和其自身的LayoutParams来共同确定,对于普通的View,其MeasureSpec由父容器的MeasureSpec和自身的Layoutparams来共同确定。</p> <p>对于 DecorView,在ViewRootImpl源码中的measureHierarchy有如下一段代码:</p> <pre> <code class="language-java">......... if (baseSize != 0 && desiredWindowWidth > baseSize) { childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured (" + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")"); if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) { goodMeasure = true; .........</code></pre> <p>我们查看一下getRootMeasureSpec方法的源码:</p> <pre> <code class="language-java">private static int getRootMeasureSpec(int windowSize, int rootDimension) { int measureSpec; switch (rootDimension) { case ViewGroup.LayoutParams.MATCH_PARENT: // Window can't resize. Force root view to be windowSize. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY); break; case ViewGroup.LayoutParams.WRAP_CONTENT: // Window can resize. Set max size for root view. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST); break; default: // Window wants to be an exact size. Force root view to be that size. measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY); break; } return measureSpec; }</code></pre> <p>从上面的代码中就可以很容理解DecorView的MeasureSpec是如何产生的,rootDimension就是DecorView自身的LayoutParams,然后会根据这个值进行判断</p> <p>LayoutParams.MATCH_PARENT:DecorView的MeasureSpec被赋值为精确模式,DecorView的大小就是Window的大小</p> <p>ViewGroup.LayoutParams.WRAP_CONTENT:DecorView的MeasureSpec被赋值为最大模式,DecorView的大小不定,但是不能超过Window的大小</p> <p>默认情况:DecorView的MeasureSpec被赋值为精确模式,DecorView的大小为自身LayoutParams设置的值,也就是rootDimension</p> <p>接着是对于普通的View,也就是布局中的View,它的Measure过程由ViewGroup传递而来,其中有一个方法是measureChildWithMargins</p> <pre> <code class="language-java">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); }</code></pre> <p>在对子view进行measure之前会先调用getChildMeasureSpec方法来获取子view的MeasureSpec,从这段代码就可以看出来子view的MeasureSpec的确定与父容器的MeasureSpec(parentWidthMeasureSpec)还有自身的LayoutParams(lp.height和lp.width),还有View自己的Margin和Padding有关</p> <p>接下来查看getChildMeasureSpec方法源码:</p> <pre> <code class="language-java">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); }</code></pre> <p>这里参数中的padding是指父容器的padding,这里是父容器所占用的空间,所以子view能使用的空间要减去这个padding的值。同时这个方法内部其实就是根据父容器的MeasureSpec结合子view的LayoutParams来确定子view的MeasureSpec</p> <h2>View的绘制流程</h2> <p>measure的过程如果只是一个View,那么通过measure方法就完成了其测量的过程,如果是一个ViewGroup,除了测量自身外,还会调用子孩子的measure方法</p> <p>1.View的measure过程View的measure过程由其measure方法完成,其中有下面一段内容</p> <pre> <code class="language-java">......... 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; } .........</code></pre> <p>可以知道View的measure方法内,其实调用了自身的onMeasure方法</p> <pre> <code class="language-java">protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); } //里面有一个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; }</code></pre> <p>一般我们只需要看MeasureSpec.AT_MOST和MeasureSpec.EXACTLY两种情况,这两种情况返回的result其实都是measureSpec中取得的specSize,这个specSize就是View测量后的大小,这里之所以是View测量后的大小,是因为View的最终大小是在layout阶段确定的,所以要加已区分,一般情况下View测量大小和最终大小是一样的。</p> <p>UNSPECIFIED情况下,result的值就是getSuggestedMinimumWidth()方法和getSuggestedMinimumHeight()返回的值,查看这两个方法</p> <pre> <code class="language-java">protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); } protected int getSuggestedMinimumHeight() { return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); }</code></pre> <p>从getSuggestedMinimumWidth代码可以看出,如果View没有设置背景,那么宽度就为mMinWidth,这个值对应android:minWidth这个属性所设定的值,如果View设置了背景,则为max(mMinWidth, mBackground.getMinimumWidth())</p> <pre> <code class="language-java">public int getMinimumWidth() { final int intrinsicWidth = getIntrinsicWidth(); return intrinsicWidth > 0 ? intrinsicWidth : 0; }</code></pre> <p>查看mBackground.getMinimumWidth()方法,它其实是Drawable的方法,如果intrinsicHeight也就是原始的宽度不为0,就返回它,如果为0,就返回0。</p> <p>从View的getDefaultSize方法可以得出结论:View的宽高由specSize决定,如果我们通过继承View来自定义控件需要重写onMeasure方法,并设置WRAP_CONTENT时的大小,否则在布局中使用WRAP_CONTENT相当于使用MATCH_PARENT</p> <p>原因:因为View在布局中使用WRAP_CONTENT就相当于specMode为AT_MOST,而这种情况下,result = specSize,这个specSize的大小为parentSize, parentSize就是父容器目前可用的大小,也就是父容器当前剩余空间的大小,那这时候和在布局中使用MATCH_PARENT效果是一样的</p> <p>所以在AT_MOST模式下,我们一般都会给View设定默认的内部宽高,并在WRAP_CONTENT时设置此宽高即可。</p> <p>可以通过查看TextView、ImageView的源码,可以得知在WRAP_CONTENT下,onMeasure方法均做了特殊的处理,下面是TextView的onMeasure中的一段内容</p> <pre> <code class="language-java">if (widthMode == MeasureSpec.AT_MOST) { width = Math.min(widthSize, width); }</code></pre> <p>2.ViewGroup的measure流程ViewGroup是一个抽象类,它没有重写View的onMeasure方法,而是自己提供了一个measureChildren方法</p> <pre> <code class="language-java">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); } } }</code></pre> <p>里面会对子元素进行遍历,然后调用measureChild方法去测量每一个子元素的宽高</p> <pre> <code class="language-java">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); }</code></pre> <p>在对子view进行measure之前会先调用getChildMeasureSpec方法来获取子孩子的MeasureSpec,从这段代码就可以看出来子view的MeasureSpec的确定与父容器的MeasureSpec(parentWidthMeasureSpec和parentHeightMeasureSpec)还有自身的LayoutParams(lp.height和lp.width),还有View自己的Margin和Padding有关,最后就是调用子view的measure方法</p> <p>ViewGroup并没有去定义测量的具体过程,这是因为ViewGroup是一个抽象类,其onMeasure方法需要各个子类去实现,因为每个ViewGroup的实现类,例如LinearLayout,RelativeLayout等的布局方式都是不同的,所以不可能一概而论的来写onMeasure方法。</p> <p>接下来分析LinearLayout的onMeasure方法:</p> <pre> <code class="language-java">protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mOrientation == VERTICAL) { measureVertical(widthMeasureSpec, heightMeasureSpec); } else { measureHorizontal(widthMeasureSpec, heightMeasureSpec); } }</code></pre> <p>查看measureVertical方法</p> <pre> <code class="language-java">// See how tall everyone is. Also remember max width. for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); if (child == null) { mTotalLength += measureNullChild(i); continue; } if (child.getVisibility() == View.GONE) { i += getChildrenSkipCount(child, i); continue; } if (hasDividerBeforeChildAt(i)) { mTotalLength += mDividerHeight; } LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); totalWeight += lp.weight; if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) { // Optimization: don't bother measuring children who are going to use // leftover space. These views will get measured again down below if // there is any leftover space. final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin); skippedMeasure = true; } else { int oldHeight = Integer.MIN_VALUE; if (lp.height == 0 && lp.weight > 0) { // heightMode is either UNSPECIFIED or AT_MOST, and this // child wanted to stretch to fill available space. // Translate that to WRAP_CONTENT so that it does not end up // with a height of 0 oldHeight = 0; lp.height = LayoutParams.WRAP_CONTENT; } // Determine how big this child would like to be. If this or // previous children have given a weight, then we allow it to // use all available space (and we will shrink things later // if needed). measureChildBeforeLayout( child, i, widthMeasureSpec, 0, heightMeasureSpec, totalWeight == 0 ? mTotalLength : 0); if (oldHeight != Integer.MIN_VALUE) { lp.height = oldHeight; } final int childHeight = child.getMeasuredHeight(); final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child)); if (useLargestChild) { largestChildHeight = Math.max(childHeight, largestChildHeight); } } /** * If applicable, compute the additional offset to the child's baseline * we'll need later when asked {@link #getBaseline}. */ if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) { mBaselineChildTop = mTotalLength; } // if we are trying to use a child index for our baseline, the above // book keeping only works if there are no children above it with // weight. fail fast to aid the developer. if (i < baselineChildIndex && lp.weight > 0) { throw new RuntimeException("A child of LinearLayout with index " + "less than mBaselineAlignedChildIndex has weight > 0, which " + "won't work. Either remove the weight, or don't set " + "mBaselineAlignedChildIndex."); } boolean matchWidthLocally = false; if (widthMode != MeasureSpec.EXACTLY && lp.width == LayoutParams.MATCH_PARENT) { // The width of the linear layout will scale, and at least one // child said it wanted to match our width. Set a flag // indicating that we need to remeasure at least that view when // we know our width. matchWidth = true; matchWidthLocally = true; } final int margin = lp.leftMargin + lp.rightMargin; final int measuredWidth = child.getMeasuredWidth() + margin; maxWidth = Math.max(maxWidth, measuredWidth); childState = combineMeasuredStates(childState, child.getMeasuredState()); allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT; if (lp.weight > 0) { /* * Widths of weighted Views are bogus if we end up * remeasuring, so keep them separate. */ weightedMaxWidth = Math.max(weightedMaxWidth, matchWidthLocally ? margin : measuredWidth); } else { alternativeMaxWidth = Math.max(alternativeMaxWidth, matchWidthLocally ? margin : measuredWidth); } i += getChildrenSkipCount(child, i); }</code></pre> <p>遍历子元素,调用他们的measureChildBeforeLayout方法,这个方法内会测量子孩子的宽高,并且有一个mTotalLength来记录LinearLayout 在竖直方向的初步高度,每测量一次子元素,mTotalLength都会增加,增加部分包括子元素的高度以及子元素竖直方向的margin</p> <pre> <code class="language-java">void measureChildBeforeLayout(View child, int childIndex, int widthMeasureSpec, int totalWidth, int heightMeasureSpec, int totalHeight) { measureChildWithMargins(child, widthMeasureSpec, totalWidth, heightMeasureSpec, totalHeight); } 里面调用了child.measure方法,也就是子孩子的measure方法 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); }</code></pre> <p>当子元素测量完毕后,LinearLayout会测量自身的大小,对于竖直的LinearLayout,它在水平方向上的测量过程,遵循View的测量过程,在竖直方向上,如果采用的是match_parent或者具体的数值,那么它的测量过程和View的一致,即高度为specSize;如果它的布局中高度采用wrap_content,那么高度是子元素所占用的高度总和,但这个和不能超过父容器的剩余空间,当然还要考虑padding,竖直方向的结论可以从下面代码得知:</p> <pre> <code class="language-java">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); }</code></pre> <p>有时候onMeasure中拿到的测量宽高可能是不准确的,比较好的习惯是在onLayout中去获取View的测量宽高和最终宽高</p> <p>在Activity中,在onCreate,onStart,onResume中均无法正确获得View的宽高信息,这是因为measure和Activity的生命周期是不同步的,所以很可能View没有测量完毕,获得的宽高是0.</p> <p>measure总结1.measure过程主要就是从顶层父View向子View递归调用view.measure方法(measure中又回调onMeasure方法)的过程。具体measure核心主要有如下几点:</p> <p>2.MeasureSpec(View的内部类)测量规格为int型,值由高2位规格模式specMode和低30位具体尺寸specSize组成。其中specMode只有三种值:</p> <pre> <code class="language-java">MeasureSpec.EXACTLY //确定模式,父View希望子View的大小是确定的,由specSize决定; MeasureSpec.AT_MOST //最多模式,父View希望子View的大小最多是specSize指定的值; MeasureSpec.UNSPECIFIED //未指定模式,父View完全依据子View的设计值来决定;</code></pre> <p>3.View的measure方法是final的,不允许重载,View子类只能重载onMeasure来完成自己的测量逻辑。</p> <p>4.最顶层DecorView测量时的MeasureSpec是由ViewRootImpl中getRootMeasureSpec方法确定的(LayoutParams宽高参数均为MATCH_PARENT,specMode是EXACTLY,specSize为物理屏幕大小)。</p> <p>5.ViewGroup类提供了measureChild,measureChild和measureChildWithMargins方法,简化了父子View的尺寸计算。</p> <p>6.只要是ViewGroup的子类就必须要求LayoutParams继承子MarginLayoutParams,否则无法使用layout_margin参数。</p> <p>7.View的布局大小由父View和子View共同决定。</p> <p>8.使用View的getMeasuredWidth()和getMeasuredHeight()方法来获取View测量的宽高,必须保证这两个方法在onMeasure流程之后被调用才能返回有效值。</p> <p>layout的过程ViewGroup的位置确定后,它在onLayout中会遍历所有的子元素并调用子元素layout方法,子元素layout方法中又会调用onLayout方法,View的layout方法确定自身的位置,而onLayout方法方法确定子孩子的位置</p> <pre> <code class="language-java">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<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; }</code></pre> <p>layout方法的大致流程如下:首先会通过setFrame方法来确定mLeft;mTop;mBottom;</p> <p>mRight;只要这四个点一旦确定,那么View在父容器中的位置就确定了,接着会调用onLayout方法,该方法目的是父容器来确定子元素的位置,无论是View还是ViewGroup都没有实现onLayout方法,我们查看LinearLayout的onLayout方法</p> <pre> <code class="language-java">@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); } }</code></pre> <p>查看layoutVertical中关键代码</p> <pre> <code class="language-java">for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child == null) { childTop += measureNullChild(i); } else if (child.getVisibility() != GONE) { final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); int gravity = lp.gravity; if (gravity < 0) { gravity = minorGravity; } final int layoutDirection = getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection); switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = paddingLeft + ((childSpace - childWidth) / 2) + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = childRight - childWidth - lp.rightMargin; break; case Gravity.LEFT: default: childLeft = paddingLeft + lp.leftMargin; break; } if (hasDividerBeforeChildAt(i)) { childTop += mDividerHeight; } childTop += lp.topMargin; setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child); i += getChildrenSkipCount(child, i); } }</code></pre> <p>这个方法会遍历所有的子元素并调用setChildFrame方法来为子元素指定对应的位置,其中childTop的数值会不断的增大,这意味着后面的子元素还位于靠下的位置,刚好符合竖直的LinearLayout的特性,setChildFrame方法中不过是调用了子元素的Layout方法而已</p> <pre> <code class="language-java">private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); }</code></pre> <p>同时,会发现setChildFrame中的width和height实际上就是子元素的测量宽高</p> <pre> <code class="language-java">final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight();</code></pre> <p>View的layout方法中会通过setFrame方法去设置子元素四个顶点的位置,这样子元素的位置就可以确定</p> <pre> <code class="language-java">int oldWidth = mRight - mLeft; int oldHeight = mBottom - mTop; int newWidth = right - left; int newHeight = bottom - top; boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); // Invalidate our old position invalidate(sizeChanged); mLeft = left; mTop = top; mRight = right; mBottom = bottom; mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);</code></pre> <p>接下来是View的getWidth和getHeight方法,结合里面的实现,可以发现他们分别返回的就是View测量的宽度和高度</p> <pre> <code class="language-java">@ViewDebug.ExportedProperty(category = "layout") public final int getWidth() { return mRight - mLeft; } /** * Return the height of your view. * * @return The height of your view, in pixels. */ @ViewDebug.ExportedProperty(category = "layout") public final int getHeight() { return mBottom - mTop; }</code></pre> <p>layout总结1.layout也是从顶层父View向子View的递归调用view.layout方法的过程,即父View根据上一步measure子View所得到的布局大小和布局参数,将子View放在合适的位置上。</p> <p>2.View.layout方法可被重载,ViewGroup.layout为final的不可重载,ViewGroup.onLayout为abstract的,子类必须重载实现自己的位置逻辑。</p> <p>3.measure操作完成后得到的是对每个View经测量过的measuredWidth和measuredHeight,layout操作完成之后得到的是对每个View进行位置分配后的mLeft、mTop、mRight、mBottom,这些值都是相对于父View来说的。</p> <p>4.凡是layout_XXX的布局属性基本都针对的是包含子View的ViewGroup的,当对一个没有父容器的View设置相关layout_XXX属性是没有任何意义的。</p> <p>5.使用View的getWidth()和getHeight()方法来获取View测量的宽高,必须保证这两个方法在onLayout流程之后被调用才能返回有效值。</p> <p><strong>draw的过程</strong></p> <p>View的绘制过程遵循以下几步:</p> <p>1)绘制背景background.draw(canvas)</p> <p>2)绘制自己(onDraw)</p> <p>3)绘制 children(dispatchDraw)</p> <p>4)绘制装饰(onDrawScrollBars)</p> <pre> <code class="language-java">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); // 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; } /* * 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); // 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); }</code></pre> <p>View的绘制过程的传递是通过dispatchDraw实现的,dispatchdraw会遍历调用所有子元素的draw方法。如此draw事件就一层一层的传递下去。</p> <p>draw总结1.如果该View是一个ViewGroup,则需要递归绘制其所包含的所有子View。</p> <p>2.View默认不会绘制任何内容,真正的绘制都需要自己在子类中实现。</p> <p>3.View的绘制是借助onDraw方法传入的Canvas类来进行的。</p> <p>4.在获取画布剪切区(每个View的draw中传入的Canvas)时会自动处理掉padding,子View获取Canvas不用关注这些逻辑,只用关心如何绘制即可。</p> <p>5.默认情况下子View的ViewGroup.drawChild绘制顺序和子View被添加的顺序一致,但是你也可以重载ViewGroup.getChildDrawingOrder()方法提供不同顺序。</p> <p>参考资料</p> <p>《Android开发艺术探索》</p> <p> </p> <p>来自:http://blog.csdn.net/u012124438/article/details/71435787</p> <p> </p>