当前位置:   article > 正文

view的onMeasure,onLayout,onDraw源码分析_onmeasure onlayout ondraw

onmeasure onlayout ondraw

1, View三部曲

在oncreate方法中加载解析完xml资源创建view对象之后,Activity中的makeVisible方法会将这些对象依次测量,确定位置并且显示在幕布上。总体的流程图如下,


重点分析onMeasure,onLayout,和onDraw方法。

1.1 onMeasure

measure是测量的意思,那么onMeasure()方法顾名思义就是用于测量视图的大小的.

1.1.1 view

首先看没有子view的测量方法.

  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  2. setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
  3. getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
  4. }
  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. }

MeasureSpec的值由specSize和specMode共同组成的,其中specSize记录的是大小(后30位),specMode记录的是规格(前2位). specMode一共有三种类型。

变量widthMeasureSpec和heightMeasureSpec都是ViewRoot的performTraversals方法中获取的,

  1. int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  2. int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  1. private static int getRootMeasureSpec(int windowSize, int rootDimension) {
  2. int measureSpec;
  3. switch (rootDimension) {
  4. case ViewGroup.LayoutParams.MATCH_PARENT:
  5. // Window can't resize. Force root view to be windowSize.
  6. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
  7. break;
  8. case ViewGroup.LayoutParams.WRAP_CONTENT:
  9. // Window can resize. Set max size for root view.
  10. measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
  11. break;
  12. default:
  13. // Window wants to be an exact size. Force root view to be that size.
  14. measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
  15. break;
  16. }
  17. return measureSpec;
  18. }

根视图总是会充满全屏的。

1.1.2 ViewGroup

既然子view都实现了o

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

闽ICP备14008679号