梳理 Android 源码中 View 的工作原理
GusGomes
8年前
<p>在View的工作过程中, 执行三大流程完成显示, 测量(measure)流程, 布局(layout)流程, 绘制(draw)流程. 从 performTraversals 方法开始, <strong>测量(measure)</strong> View的高度(Height)与宽度(Width), <strong>布局(layout)</strong> View在父容器中的位置, <strong>绘制(draw)</strong> View在屏幕上.</p> <p>通过源码, 循序渐进, 解析View的工作原理和三大流程.</p> <p style="text-align:center"><img src="https://simg.open-open.com/show/461fa9bbed4b83bb568021a2eafbe3a5.png"></p> <h2><strong>ViewRoot</strong></h2> <p>ViewRoot连结 <strong>WindowManager</strong> 与 <strong>DecorView</strong> , 调用流程 performTraversals , 并依次调用 performMeasure , performLayout , performDraw .</p> <p>Measure调用 onMeasure , Layout调用 onLayout , Draw调用 onDraw 与 dispatchDraw . Measure中, 调用 getMeasuredHeight 与 getMeasuredWidth 获取绘制好的高度与宽度; Layout中, 调用 getHeight 与 getWidth 获取布局好的高度与宽度. <strong>注意</strong> 因时机不同, Measure的度量可能不同于Layout的度量.</p> <p>Measure与Layout使用onMeasure与onLayout遍历调用子View的方法. Draw使用onDraw绘制View本身, 使用onDispatch绘制子View.</p> <h2><strong>DecorView</strong></h2> <p>DecorView是顶层View, 即FrameLayout, 其中包含竖直方向的LinearLayout, 标题 <strong>titlebar</strong> , 内容 <strong>android.R.id.content</strong> . 获取 setContentView 的布局的方法.</p> <pre> <code class="language-java">ViewGroup content = (ViewGroup) findViewById(android.R.id.content); // 父布局 View view = content.getChildAt(0); // 内容布局</code></pre> <h2><strong>MeasureSpec</strong></h2> <p>View的 <strong>MeasureSpec</strong> , MeasureSpec是32位int值, 高2位是 <strong>SpecMode</strong> , 低30位是 <strong>SpecSize</strong> , 选择测量的模式, 设置测量的大小.</p> <p>SpecMode三种类型, <strong>UNSPECIFIED</strong> 不做任何限制; <strong>EXACTLY</strong> 精确大小, 即match_parent和具体数值; <strong>AT_MOST</strong> 不能超过最大距离, 即wrap_content.</p> <p>在onMeasure中, View使用MeasureSpec测量View的大小, 由父布局的 <strong>MeasureSpec</strong> 与自身的 <strong>LayoutParams</strong> 决定; DecorView是根View, 由系统的 <strong>窗口尺寸</strong> 与自身的LayoutParams决定.</p> <p>父View负责绘制子View, 子View的大小由 <strong>父View的模式与大小</strong> 与 <strong>自身的模式与大小</strong> 决定. 简而言之, <strong>父容器的MeasureSpec</strong> 与 <strong>子View的LayoutParams</strong> 决定 <strong>子View的MeasureSpec</strong> .</p> <h2><strong>Measure</strong></h2> <p>Measure测量View的高度与宽度. View调用onMeasure完成测量; ViewGroup遍历子View的onMeasure, 再递归汇总.</p> <h3><strong>View</strong></h3> <p>View的 measure 方法是禁止继承的, 调用 onMeasure 方法, 自定义View通过 onMeasure 方法设置测量大小. onMeasure 方法调用 setMeasuredDimension 设置测量大小.</p> <pre> <code class="language-java">protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }</code></pre> <p>宽与高使用 getDefaultSize 获取默认值, 参数是推荐最小值(getSuggestedMinimumX)与指定测量规格(xMeasureSpec).</p> <pre> <code class="language-java">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>注意 <strong>AT_MOST</strong> 模式, 使用最小宽度, 当未设置时, 使用父容器的最大值, 因此自定义View需要设置默认值, 否者 wrap_content 与 match_parent 功能相同.</p> <p>参考 <strong>ViewGroup</strong> . 当子View的布局参数是WRAP_CONTENT时, 无论父View的类型, 都是父View的空闲值.</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: // ... } else if (childDimension == LayoutParams.WRAP_CONTENT) { // Child wants to determine its own size. It can't be // bigger than us. resultSize = size; // 父View空闲宽度 resultMode = MeasureSpec.AT_MOST; } break; // Parent has imposed a maximum size on us case 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; // 父View空闲宽度 resultMode = MeasureSpec.AT_MOST; } break; // ... } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); }</code></pre> <p>自定义View需要设置 wrap_content 状态下的测量值, 可以参考 <strong>TextView</strong> 与 <strong>ImageView</strong> .</p> <pre> <code class="language-java">private int mMinWidth = 256; // 指定默认最小宽度 private int mMinHeight = 256; // 指定默认最小高度 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mMinWidth, mMinHeight); } else if (widthSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(mMinWidth, heightSpecSize); } else if (heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize, mMinHeight); } }</code></pre> <p>获取建议的最小宽度, 在已设置最小宽度 android:minWidth 与背景 android:background 的最小宽度的 <strong>最大值</strong> , 默认返回0.</p> <pre> <code class="language-java">protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); }</code></pre> <h3><strong>ViewGroup</strong></h3> <p>ViewGroup使用 onMeasure 绘制自己, 并遍历子View的onMeasure递归绘制.</p> <p>使用 measureChildren 方法绘制全部子View.</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>子View绘制使用 measureChild , 最终汇总.</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>不同的ViewGroup实现不同的onMeasure方法, 如LinearLayout, RelativeLayout, FrameLayout等.</p> <h2><strong>测量值</strong></h2> <p>View的onMeasure与Activity的生命周期不一致, 无法在生命周期的方法中, 获取测量值. 测量值需要在测量完成后计算.</p> <p>onWindowFocusChanged方法, 在Activity窗口获得或失去焦点时都会被调用, 即在onResume与onPause执行时会调用, 此时, View的测量(Measure)已经完成, 获取测量值.</p> <pre> <code class="language-java">private int mWidth; // 宽度 private int mHeight; // 高度 /** * 在Activity获得焦点时, 获取测量宽度与高度 * * @param hasFocus 关注 */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { mWidth = getContentView().getMeasuredWidth(); mHeight = getContentView().getMeasuredHeight(); } } /** * 获取Activity的ContentView * * @return ContentView */ private View getContentView() { ViewGroup view = (ViewGroup) getWindow().getDecorView(); FrameLayout content = (FrameLayout) view.getChildAt(0); return content.getChildAt(0); }</code></pre> <p>在View的 <strong>消息队列</strong> 尾部, 获取测量值. View的测量过程是在消息队列中完成的, 完成全部的系统消息, 才会执行用户消息.</p> <pre> <code class="language-java">private int mWidth; // 宽度 private int mHeight; // 高度 @Override protected void onResume() { super.onResume(); final View view = getContentView(); view.post(new Runnable() { @Override public void run() { mWidth = view.getMeasuredWidth(); mHeight = view.getMeasuredHeight(); } }); }</code></pre> <h2><strong>Layout</strong></h2> <p>View使用 layout 确定位置, layout调用 onLayout , 在onLayout中调用子View的layout.</p> <p>layout先调用setFrame确定View的四个顶点, 即left, right, top, bottom, 再调用onLayout确定子View的位置. 在onLayout中, 调用setChildFrame确定子View的四个顶点, 子View再调用layout.</p> <p>在一般情况下, View的测量(Measure)宽高与布局(Layout)宽高是相同的, 确定时机不同, 测量要早于布局.</p> <p>如果在View的layout中, 重新设置宽高, 则测量宽高与布局不同, 不过此类方法, 并无任何意义.</p> <pre> <code class="language-java">@Override public void layout(int l, int t, int r, int b) { super.layout(l, t, r + 256, b + 256); // 右侧底部, 各加256, 无意义 }</code></pre> <h2><strong>Draw</strong></h2> <p>View的绘制(Draw)过程, 首先绘制背景, 即 android:backgroud ; 其次绘制自己, 即 onDraw ; 再次绘制子View, 即 dispatchDraw ; 最后绘制页面装饰, 如滚动条.</p> <pre> <code class="language-java">public void draw(Canvas canvas) { // ... /* * 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 // 第三步, 绘制子View dispatchDraw(canvas); // Step 6, draw decorations (scrollbars) // 第四步, 绘制装饰 onDrawScrollBars(canvas); if (mOverlay != null && !mOverlay.isEmpty()) { mOverlay.getOverlayView().dispatchDraw(canvas); } // we're done... return; } // ... }</code></pre> <p>关注源码的绘制 draw 流程: drawBackground -> onDraw -> dispatchDraw -> onDrawScrollBars</p> <p>View的工作原理来源于三大流程, 测量(measure)流程, 布局(layout)流程, 绘制(draw)流程. 通过源码理解View的三大流程, 有利于提升程序设计理念, 与开发质量.</p> <p> </p> <p> </p> <p>来自:http://www.jianshu.com/p/17b372ef3f41</p> <p> </p>