当前位置:   article > 正文

Android:View体系之UI 的绘制流程及原理 (源码分析+掌握,看这一篇就足够!)_android ui布局绘制原理

android ui布局绘制原理

转载请标明出处!

目录

一 概述

1.1 Android的View继承关系图

1.2 Android的视图坐标

1.2.1 安卓坐标系

1.2.2 视图坐标系

1.2.3 常用方法

二 View的事件分发

三 View的工作流程

3.1 概述

3.2 测量

3.2.1 预备知识MeasureSpec(重要)

3.2.2 MeasureSpec的SpecMode分类(模式)

3.2.3 测绘过程

3.2.4 测绘源码分析,以DecorView为例

3.3 布局

3.3.1 布局源码分析,以FrameLayout为例

3.4 绘制

3.4.1 绘制 源码分析,以FrameLayout为例


一 概述

1.1 Android的View继承关系图

View是安卓所有控件的父基类。

 

1.2 Android的视图坐标

1.2.1 安卓坐标系

获取办法:MotionEvent提供的getRawX()和getRawY();

1.2.2 视图坐标系

1.2.3 常用方法

View获取自身宽高

getHeight()获取View自身高度
getWidth()获取View自身宽度

View到其父控件(ViewGroup)的距离:

getTop()获取View自身顶边到其父布局顶边的距离
getLeft()获取View自身左边到其父布局左边的距离
getRight()获取View自身右边到其父布局左边的距离
getBottom()获取View自身底边到其父布局顶边的距离

 

MotionEvent提供的方法

我们看上图那个深蓝色的点,假设就是我们触摸的点,我们知道无论是View还是ViewGroup,最终的点击事件都会由onTouchEvent(MotionEvent event)方法来处理,MotionEvent也提供了各种获取焦点坐标的方法:

getX()获取点击事件距离控件左边的距离,即视图坐标
getY()获取点击事件距离控件顶边的距离,即视图坐标
getRawX()获取点击事件距离整个屏幕左边距离,即绝对坐标
getRawY()取点击事件距离整个屏幕顶边的的距离,即绝对坐标

二 View的事件分发

点击事件分发:点击屏幕就会产生触摸事件,这个事件被封装成了一个类:MotionEvent。当这个MotionEvent产生后,系统就会将这个MotionEvent传递给View的各个层级,MotionEvent在View层级传递的过程,就是点击事件分发。

点击事件有三个重要的方法:

dispatchTouchEvent(MotionEvent ev)用来进行事件的分发
onInterceptTouchEvent(MotionEvent ev)用来进行事件的拦截,在dispatchTouchEvent()中调用,需要注意的是View没有提供该方法
onTouchEvent(MotionEvent ev)用来处理点击事件,在dispatchTouchEvent()方法中进行调用

点击事件分发的这三个重要方法的关系,用伪代码来简单表示就是:

  1. public boolean dispatchTouchEvent(MotionEvent ev) {
  2. boolean result=false;
  3. if(onInterceptTouchEvent(ev)){
  4. result=super.onTouchEvent(ev);
  5. }else{
  6. result=child.dispatchTouchEvent(ev);
  7. }
  8. return result;

 这个U型图就很好的解释了事件分发:


 

总结:dispatchTouchEvent代表分发事件,onInterceptTouchEvent()代表拦截事件,onTouchEvent()代表消耗事件,由自己处理。


三 View的工作流程

3.1 概述

measure:测量View的宽高;测量;

layout:用来确定View的位置;布局;

draw:则用来绘制View;绘制;

3.2 测量

3.2.1 预备知识MeasureSpec(重要)

       MeasureSpec是View的静态内部类;View的测量就是测量View的宽高,而View的宽高被封装到了MeasureSpec里面。

       测量的过程实际上就是如何确定View的MeasureSpec的过程,而MeasureSpec主要包含两个参数:模式+尺寸。

       MeasureSpec是一个32位int值,前2位表示SpecMode即模式  ,后30位表示SpecSize即尺寸。

 

3.2.2 MeasureSpec的SpecMode分类(模式)

UNSPECIFIED

public static final int UNSPECIFIED = 0 << MODE_SHIFT; 00000000000000000000000000000000

父容器不对View做任何限制,系统内部使用

EXACTLY  
public static final int EXACTLY     = 1 << MODE_SHIFT; 01000000000000000000000000000000
父容器检测出View的大小,Vew的大小就是SpecSize LayoutPamras match_parent 固定大小

AT_MOST
public static final int AT_MOST     = 2 << MODE_SHIFT; 10000000000000000000000000000000
父容器指定一个可用大小,View的大小不能超过这个值,LayoutPamras wrap_content

 

3.2.3 测绘过程

ViewGroup的测绘过程 :

measure --> onMeasure(测量子控件的宽高)--> setMeasuredDimension -->setMeasuredDimensionRaw(保存自己的宽高)


View的测绘过程:

measure --> onMeasure --> setMeasuredDimension -->setMeasuredDimensionRaw(保存自己的宽高)

 

3.2.4 测绘源码分析,以DecorView为例

首先在ViewRootImpl中,执行performMeasure方法:

  1. private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
  2. if (mView == null) {
  3. return;
  4. }
  5. Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
  6. try {
  7. mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  8. } finally {
  9. Trace.traceEnd(Trace.TRACE_TAG_VIEW);
  10. }
  11. }

点击mView.measure方法,会进入View的measure方法(标注1)(view的该方法为final,不能被重写),如下:

  1. public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  2. boolean optical = isLayoutModeOptical(this);
  3. if (optical != isLayoutModeOptical(mParent)) {
  4. Insets insets = getOpticalInsets();
  5. int oWidth = insets.left + insets.right;
  6. int oHeight = insets.top + insets.bottom;
  7. widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth);
  8. heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
  9. }
  10. // Suppress sign extension for the low bytes
  11. long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
  12. if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);
  13. final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
  14. // Optimize layout by avoiding an extra EXACTLY pass when the view is
  15. // already measured as the correct size. In API 23 and below, this
  16. // extra pass is required to make LinearLayout re-distribute weight.
  17. final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec
  18. || heightMeasureSpec != mOldHeightMeasureSpec;
  19. final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
  20. && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
  21. final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec)
  22. && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
  23. final boolean needsLayout = specChanged
  24. && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize);
  25. if (forceLayout || needsLayout) {
  26. // first clears the measured dimension flag
  27. mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
  28. resolveRtlPropertiesIfNeeded();
  29. int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
  30. if (cacheIndex < 0 || sIgnoreMeasureCache) {
  31. // measure ourselves, this should set the measured dimension flag back
  32. //这里!重要的onMeasure方法,终于找到你!
  33. //这里!重要的onMeasure方法,终于找到你!
  34. //这里!重要的onMeasure方法,终于找到你!
  35. onMeasure(widthMeasureSpec, heightMeasureSpec);
  36. mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  37. } else {
  38. long value = mMeasureCache.valueAt(cacheIndex);
  39. // Casting a long to int drops the high 32 bits, no mask needed
  40. setMeasuredDimensionRaw((int) (value >> 32), (int) value);
  41. mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  42. }
  43. // flag not set, setMeasuredDimension() was not invoked, we raise
  44. // an exception to warn the developer
  45. if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
  46. throw new IllegalStateException("View with id " + getId() + ": "
  47. + getClass().getName() + "#onMeasure() did not set the"
  48. + " measured dimension by calling"
  49. + " setMeasuredDimension()");
  50. }
  51. mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
  52. }
  53. mOldWidthMeasureSpec = widthMeasureSpec;
  54. mOldHeightMeasureSpec = heightMeasureSpec;
  55. mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
  56. (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
  57. }

代码有点多,不用全看。前半部分主要是取了缓存,然后执行了 onMeasure(widthMeasureSpec, heightMeasureSpec)方法。如果缓存没读到会进行缓存的一个设置。(关于缓存可以先忽略不用管,主要是对测量做一些优化)

紧接着上面的代码段中,点击主要的onMeasure方法一探究竟:

  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  2. setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
  3. getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
  4. }

会发现,onMeasure方法里最主要调用了两个方法:setMeasuredDimension方法和getDefaultSize方法。先看下getDefaultSize方法:

  1. public static int getDefaultSize(int size, int measureSpec) {
  2. int result = size;
  3. int specMode = MeasureSpec.getMode(measureSpec);
  4. int specSize = MeasureSpec.getSize(measureSpec);
  5. switch (specMode) {
  6. case MeasureSpec.UNSPECIFIED:
  7. result = size;
  8. break;
  9. case MeasureSpec.AT_MOST:
  10. case MeasureSpec.EXACTLY:
  11. result = specSize;
  12. break;
  13. }
  14. return result;
  15. }

注意,可以看到,这里无论是AT_MOST模式还是EXACTLY模式,都是默认的specSize,所以我们在自定义View的时候,一定要重写onMeasure方法,否则match_parent和wrap_content属性时,将不起作用。

我们再来看看setMeasuredDimension方法里是什么:

  1. protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
  2. boolean optical = isLayoutModeOptical(this);
  3. if (optical != isLayoutModeOptical(mParent)) {
  4. Insets insets = getOpticalInsets();
  5. int opticalWidth = insets.left + insets.right;
  6. int opticalHeight = insets.top + insets.bottom;
  7. measuredWidth += optical ? opticalWidth : -opticalWidth;
  8. measuredHeight += optical ? opticalHeight : -opticalHeight;
  9. }
  10. setMeasuredDimensionRaw(measuredWidth, measuredHeight);
  11. }

可以看到,setMeasuredDimension方法里继续调用了setMeasuredDimensionRaw(measuredWidth, measuredHeight)方法,继续查看这个方法的详细:

  1. private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
  2. mMeasuredWidth = measuredWidth;
  3. mMeasuredHeight = measuredHeight;
  4. mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
  5. }

谢天谢地,终于到头了!可以看到,该方法对宽高成员变量赋值以及设置了一个标记位。

不要因为走得太远而忘记了为何出发,我们是在ViewRootImpl中执行performMeasure方法中的mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)不断追溯来到这边的,所以measure(测量)实质上就是确定控件的宽和高。那么控件的宽和高,他们的值又是如何确定的呢?现在我们就需要查看mView.measure(childWidthMeasureSpec, childHeightMeasureSpec)中的childWidthMeasureSpec, childHeightMeasureSpec这两个参数!

这边打个分割线便于大家理解,上方是mView.measure方法测量的源码过程解析,


接下来我们需要知道mView.measure方法的两个参数如何获取。

在ViewRootlmpl中,继续解读源码:

  1. int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  2. int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  3. if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed! mWidth="
  4. + mWidth + " measuredWidth=" + host.getMeasuredWidth()
  5. + " mHeight=" + mHeight
  6. + " measuredHeight=" + host.getMeasuredHeight()
  7. + " coveredInsetsChanged=" + contentInsetsChanged);
  8. // Ask host how big it wants to be
  9. performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

可以看到,childWidthMeasureSpec,和childHeightMeasureSpec这两个参数由getRootMeasureSpec(mWidth, lp.width)方法和getRootMeasureSpec(mHeight, lp.height)得出。以第一个为例,mWidth表示的是窗口(PhoneWindow)的宽,第二个参数表示的是顶层View的本身的宽。参数有了,我们接下来再详细进入getRootMeasureSpec这个方法里一探究竟:

  1. /**
  2. * Figures out the measure spec for the root view in a window based on it's
  3. * layout params.
  4. *
  5. * @param windowSize
  6. * The available width or height of the window
  7. *
  8. * @param rootDimension
  9. * The layout params for one dimension (width or height) of the
  10. * window.
  11. *
  12. * @return The measure spec to use to measure the root view.
  13. */
  14. private static int getRootMeasureSpec(int windowSize, int rootDimension) {
  15. int measureSpec;
  16. switch (rootDimension) {
  17. case ViewGroup.LayoutParams.MATCH_PARENT:
  18. // Window can't resize. Force root view to be windowSize.
  19. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
  20. break;
  21. case ViewGroup.LayoutParams.WRAP_CONTENT:
  22. // Window can resize. Set max size for root view.
  23. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
  24. break;
  25. default:
  26. // Window wants to be an exact size. Force root view to be that size.
  27. measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
  28. break;
  29. }
  30. return measureSpec;
  31. }

注释写的很详细了,可以看到,该方法里对测量的view就行了switch判断,根据view的match_parent属性/wrap_content属性设置了measureSpec的不同模式(EXACTLY/AT_MOST)。

又这个方法我们可以得出结论:DecorView的MeasureSpec方法由窗口大小和自己的LayoutParams决定。具体的决定规则逻辑在如上代码中,具象下来可以总结如下:

继续分析。刚刚我们已经确定了这两个参数的由来。实际上这两个参数确定了DccorView的模式和尺寸(注意子view的测量还没有,过程才刚开始)。

继续分割一下避免混乱,上面是mView.measure方法的两个参数由来,


接下来我们继续分析mView.measure方法。

mView.measure(也就是View的measure方法,这里的mView就是DecorView)中调用onMeasure方法。我们知道DecorView实际上是集成FrameLayout的,所以我们直接去FrameLayout中看看这个onMeasure方法的具体实现:

  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  2. int count = getChildCount();
  3. final boolean measureMatchParentChildren =
  4. MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
  5. MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
  6. mMatchParentChildren.clear();
  7. int maxHeight = 0;
  8. int maxWidth = 0;
  9. int childState = 0;
  10. for (int i = 0; i < count; i++) {
  11. final View child = getChildAt(i);
  12. if (mMeasureAllChildren || child.getVisibility() != GONE) {
  13. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
  14. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
  15. maxWidth = Math.max(maxWidth,
  16. child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
  17. maxHeight = Math.max(maxHeight,
  18. child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
  19. childState = combineMeasuredStates(childState, child.getMeasuredState());
  20. if (measureMatchParentChildren) {
  21. if (lp.width == LayoutParams.MATCH_PARENT ||
  22. lp.height == LayoutParams.MATCH_PARENT) {
  23. mMatchParentChildren.add(child);
  24. }
  25. }
  26. }
  27. }
  28. // Account for padding too
  29. maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
  30. maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
  31. // Check against our minimum height and width
  32. maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
  33. maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
  34. // Check against our foreground's minimum height and width
  35. final Drawable drawable = getForeground();
  36. if (drawable != null) {
  37. maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
  38. maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
  39. }
  40. setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
  41. resolveSizeAndState(maxHeight, heightMeasureSpec,
  42. childState << MEASURED_HEIGHT_STATE_SHIFT));
  43. count = mMatchParentChildren.size();
  44. if (count > 1) {
  45. for (int i = 0; i < count; i++) {
  46. final View child = mMatchParentChildren.get(i);
  47. final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  48. final int childWidthMeasureSpec;
  49. if (lp.width == LayoutParams.MATCH_PARENT) {
  50. final int width = Math.max(0, getMeasuredWidth()
  51. - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
  52. - lp.leftMargin - lp.rightMargin);
  53. childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
  54. width, MeasureSpec.EXACTLY);
  55. } else {
  56. childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
  57. getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
  58. lp.leftMargin + lp.rightMargin,
  59. lp.width);
  60. }
  61. final int childHeightMeasureSpec;
  62. if (lp.height == LayoutParams.MATCH_PARENT) {
  63. final int height = Math.max(0, getMeasuredHeight()
  64. - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
  65. - lp.topMargin - lp.bottomMargin);
  66. childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
  67. height, MeasureSpec.EXACTLY);
  68. } else {
  69. childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
  70. getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
  71. lp.topMargin + lp.bottomMargin,
  72. lp.height);
  73. }
  74. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  75. }
  76. }
  77. }

很符合我们心理预期,FrameLayout作为容器,肯定会包含很多的子View,可以看到上面的源码方法里,也对其所有的子View进行了遍历,不难想象,它将对它的所有子View进行测量。为了验证猜想,继续点击该方法中的measureChildWithMargins中一探究竟:

  1. protected void measureChildWithMargins(View child,
  2. int parentWidthMeasureSpec, int widthUsed,
  3. int parentHeightMeasureSpec, int heightUsed) {
  4. final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  5. final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
  6. mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
  7. + widthUsed, lp.width);
  8. final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
  9. mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
  10. + heightUsed, lp.height);
  11. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  12. }

该方法中增加了对padding的处理,很容易理解不赘述。

看child.measure(childWidthMeasureSpec, childHeightMeasureSpec)方法。验证了我们的猜想,从名字就可以看出,开始对FrameLayout中的子View进行宽高 测量了。

这里有个非常重要的点:getChildMeasureSpec方法,即对子View的MeasureSpec的获取,点击看详细的getChildMeasureSpec方法实现:

  1. public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
  2. int specMode = MeasureSpec.getMode(spec);
  3. int specSize = MeasureSpec.getSize(spec);
  4. int size = Math.max(0, specSize - padding);
  5. int resultSize = 0;
  6. int resultMode = 0;
  7. switch (specMode) {
  8. // Parent has imposed an exact size on us
  9. case MeasureSpec.EXACTLY:
  10. if (childDimension >= 0) {
  11. resultSize = childDimension;
  12. resultMode = MeasureSpec.EXACTLY;
  13. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  14. // Child wants to be our size. So be it.
  15. resultSize = size;
  16. resultMode = MeasureSpec.EXACTLY;
  17. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  18. // Child wants to determine its own size. It can't be
  19. // bigger than us.
  20. resultSize = size;
  21. resultMode = MeasureSpec.AT_MOST;
  22. }
  23. break;
  24. // Parent has imposed a maximum size on us
  25. case MeasureSpec.AT_MOST:
  26. if (childDimension >= 0) {
  27. // Child wants a specific size... so be it
  28. resultSize = childDimension;
  29. resultMode = MeasureSpec.EXACTLY;
  30. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  31. // Child wants to be our size, but our size is not fixed.
  32. // Constrain child to not be bigger than us.
  33. resultSize = size;
  34. resultMode = MeasureSpec.AT_MOST;
  35. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  36. // Child wants to determine its own size. It can't be
  37. // bigger than us.
  38. resultSize = size;
  39. resultMode = MeasureSpec.AT_MOST;
  40. }
  41. break;
  42. // Parent asked to see how big we want to be
  43. case MeasureSpec.UNSPECIFIED:
  44. if (childDimension >= 0) {
  45. // Child wants a specific size... let him have it
  46. resultSize = childDimension;
  47. resultMode = MeasureSpec.EXACTLY;
  48. } else if (childDimension == LayoutParams.MATCH_PARENT) {
  49. // Child wants to be our size... find out how big it should
  50. // be
  51. resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
  52. resultMode = MeasureSpec.UNSPECIFIED;
  53. } else if (childDimension == LayoutParams.WRAP_CONTENT) {
  54. // Child wants to determine its own size.... find out how
  55. // big it should be
  56. resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
  57. resultMode = MeasureSpec.UNSPECIFIED;
  58. }
  59. break;
  60. }
  61. //noinspection ResourceType
  62. return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
  63. }

这个方法有点长,不要怕。可以看到该方法的第一个参数表示父容器的MeasureSpec的值(父容器的模式和尺寸),第二个参数padding就不说了,第三个参数表示该view本身的尺寸。该方法就通过对父容器的模式的判断,确定该子View的模式和尺寸。具体的判断逻辑可看如上代码,不详细赘述了,总结如下:

在对所有的子控件测量完成后,FrameLayout开始需要最终确定自己的宽高。继续看FrameLayout中的onMeasure方法,看它的后半段,我再粘贴下关键代码:

  1. // Account for padding too
  2. maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
  3. maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
  4. // Check against our minimum height and width
  5. maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
  6. maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
  7. // Check against our foreground's minimum height and width
  8. final Drawable drawable = getForeground();
  9. if (drawable != null) {
  10. maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
  11. maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
  12. }
  13. setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
  14. resolveSizeAndState(maxHeight, heightMeasureSpec,
  15. childState << MEASURED_HEIGHT_STATE_SHIFT));
  16. count = mMatchParentChildren.size();
  17. if (count > 1) {
  18. for (int i = 0; i < count; i++) {
  19. final View child = mMatchParentChildren.get(i);
  20. final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
  21. final int childWidthMeasureSpec;
  22. if (lp.width == LayoutParams.MATCH_PARENT) {
  23. final int width = Math.max(0, getMeasuredWidth()
  24. - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
  25. - lp.leftMargin - lp.rightMargin);
  26. childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
  27. width, MeasureSpec.EXACTLY);
  28. } else {
  29. childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
  30. getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
  31. lp.leftMargin + lp.rightMargin,
  32. lp.width);
  33. }
  34. final int childHeightMeasureSpec;
  35. if (lp.height == LayoutParams.MATCH_PARENT) {
  36. final int height = Math.max(0, getMeasuredHeight()
  37. - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
  38. - lp.topMargin - lp.bottomMargin);
  39. childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
  40. height, MeasureSpec.EXACTLY);
  41. } else {
  42. childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
  43. getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
  44. lp.topMargin + lp.bottomMargin,
  45. lp.height);
  46. }
  47. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  48. }
  49. }

可以看到,FrameLayout找到所有子控件中,最底部子控件的高,和最右边子控件的高。由此我们最终确定了Framelayout的宽高!


3.3 布局

源码看起来总是费力些,先总结如下:

View :

调用View.layout来确定自己的位置,即确定mLeft,mTop,mRight,mBottom的值,获得4个点的位置。

ViewGroup:

调用View.layout来确定自己的位置,再调用onLayout确定子View的位置。

 

3.3.1 布局源码分析,以FrameLayout为例

查看FrameLayout的onLayout方法如下:

  1. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  2. layoutChildren(left, top, right, bottom, false /* no force left gravity */);
  3. }

点击查看 layoutChildren方法:

  1. void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
  2. final int count = getChildCount();
  3. final int parentLeft = getPaddingLeftWithForeground();
  4. final int parentRight = right - left - getPaddingRightWithForeground();
  5. final int parentTop = getPaddingTopWithForeground();
  6. final int parentBottom = bottom - top - getPaddingBottomWithForeground();
  7. for (int i = 0; i < count; i++) {
  8. final View child = getChildAt(i);
  9. if (child.getVisibility() != GONE) {
  10. final LayoutParams lp = (LayoutParams) child.getLayoutParams();
  11. final int width = child.getMeasuredWidth();
  12. final int height = child.getMeasuredHeight();
  13. int childLeft;
  14. int childTop;
  15. int gravity = lp.gravity;
  16. if (gravity == -1) {
  17. gravity = DEFAULT_CHILD_GRAVITY;
  18. }
  19. final int layoutDirection = getLayoutDirection();
  20. final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
  21. final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
  22. switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
  23. case Gravity.CENTER_HORIZONTAL:
  24. childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
  25. lp.leftMargin - lp.rightMargin;
  26. break;
  27. case Gravity.RIGHT:
  28. if (!forceLeftGravity) {
  29. childLeft = parentRight - width - lp.rightMargin;
  30. break;
  31. }
  32. case Gravity.LEFT:
  33. default:
  34. childLeft = parentLeft + lp.leftMargin;
  35. }
  36. switch (verticalGravity) {
  37. case Gravity.TOP:
  38. childTop = parentTop + lp.topMargin;
  39. break;
  40. case Gravity.CENTER_VERTICAL:
  41. childTop = parentTop + (parentBottom - parentTop - height) / 2 +
  42. lp.topMargin - lp.bottomMargin;
  43. break;
  44. case Gravity.BOTTOM:
  45. childTop = parentBottom - height - lp.bottomMargin;
  46. break;
  47. default:
  48. childTop = parentTop + lp.topMargin;
  49. }
  50. child.layout(childLeft, childTop, childLeft + width, childTop + height);
  51. }
  52. }
  53. }

 可以看到, layoutChildren方法中对子View进行了遍历,对子控件进行位置的摆放。而对子控件的摆放,调用的是子控件的layout方法,也就是上面代码的最后一行。布局就是这么简单。


3.4 绘制


ViewGroup 绘制步骤:

绘制背景 drawBackground(canvas)

绘制自己onDraw(canvas)

绘制子View dispatchDraw(canvas)

绘制前景,滚动条等装饰onDrawForeground(canvas)

 

View绘制步骤:

绘制背景 drawBackground(canvas)

绘制自己onDraw(canvas)

绘制前景,滚动条等装饰onDrawForeground(canvas) 

 

绘制自定义控件的步骤:

onMeasure  --> onLayout(自定义的是容器时需要重写该方法,自定义View时可不重写该方法) --> onDraw(可选,若容器里都是系统控件,可不重写)


3.4.1 绘制 源码分析,以FrameLayout为例

找到ViewRootlmpl中的performDraw方法:

  1. private void performDraw() {
  2. if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
  3. return;
  4. } else if (mView == null) {
  5. return;
  6. }
  7. final boolean fullRedrawNeeded = mFullRedrawNeeded || mReportNextDraw;
  8. mFullRedrawNeeded = false;
  9. mIsDrawing = true;
  10. Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
  11. boolean usingAsyncReport = false;
  12. if (mReportNextDraw && mAttachInfo.mThreadedRenderer != null
  13. && mAttachInfo.mThreadedRenderer.isEnabled()) {
  14. usingAsyncReport = true;
  15. mAttachInfo.mThreadedRenderer.setFrameCompleteCallback((long frameNr) -> {
  16. // TODO: Use the frame number
  17. pendingDrawFinished();
  18. });
  19. }
  20. try {
  21. boolean canUseAsync = draw(fullRedrawNeeded);
  22. if (usingAsyncReport && !canUseAsync) {
  23. mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
  24. usingAsyncReport = false;
  25. }
  26. } finally {
  27. mIsDrawing = false;
  28. Trace.traceEnd(Trace.TRACE_TAG_VIEW);
  29. }
  30. // For whatever reason we didn't create a HardwareRenderer, end any
  31. // hardware animations that are now dangling
  32. if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
  33. final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
  34. for (int i = 0; i < count; i++) {
  35. mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
  36. }
  37. mAttachInfo.mPendingAnimatingRenderNodes.clear();
  38. }
  39. if (mReportNextDraw) {
  40. mReportNextDraw = false;
  41. // if we're using multi-thread renderer, wait for the window frame draws
  42. if (mWindowDrawCountDown != null) {
  43. try {
  44. mWindowDrawCountDown.await();
  45. } catch (InterruptedException e) {
  46. Log.e(mTag, "Window redraw count down interrupted!");
  47. }
  48. mWindowDrawCountDown = null;
  49. }
  50. if (mAttachInfo.mThreadedRenderer != null) {
  51. mAttachInfo.mThreadedRenderer.setStopped(mStopped);
  52. }
  53. if (LOCAL_LOGV) {
  54. Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
  55. }
  56. if (mSurfaceHolder != null && mSurface.isValid()) {
  57. SurfaceCallbackHelper sch = new SurfaceCallbackHelper(this::postDrawFinished);
  58. SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
  59. sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
  60. } else if (!usingAsyncReport) {
  61. if (mAttachInfo.mThreadedRenderer != null) {
  62. mAttachInfo.mThreadedRenderer.fence();
  63. }
  64. pendingDrawFinished();
  65. }
  66. }
  67. }

代码很多不用都看,找到其中的draw方法,点进去,draw()方法里代码也很多,不粘贴了,找到draw()方法里的drawSoftware方法,然后是drawSoftware方法中的mView.draw()方法。点进去即进入了View的draw()方法,如下:

  1. public void draw(Canvas canvas) {
  2. final int privateFlags = mPrivateFlags;
  3. final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
  4. (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
  5. mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
  6. /*
  7. * Draw traversal performs several drawing steps which must be executed
  8. * in the appropriate order:
  9. *
  10. * 1. Draw the background
  11. * 2. If necessary, save the canvas' layers to prepare for fading
  12. * 3. Draw view's content
  13. * 4. Draw children
  14. * 5. If necessary, draw the fading edges and restore layers
  15. * 6. Draw decorations (scrollbars for instance)
  16. */
  17. // Step 1, draw the background, if needed
  18. int saveCount;
  19. if (!dirtyOpaque) {
  20. drawBackground(canvas);
  21. }
  22. // skip step 2 & 5 if possible (common case)
  23. ...
  24. ...

可以看到,注释写的非常详细,已经把绘制的步骤一一列举出来了,省略的没有粘贴的代码就是一步步执行步骤的具体代码逻辑。

 

最后,来张神图:

 

 

参考文章

View的平滑移动:https://blog.csdn.net/itachi85/article/details/50724558

Android View体系:https://blog.csdn.net/itachi85/article/details/51577896

Android事件分发机制详解:https://juejin.im/post/5d3e5278e51d4556f76e8194#heading-18

View的工作流程:https://blog.csdn.net/qian520ao/article/details/78657084

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/742996
推荐阅读
相关标签
  

闽ICP备14008679号