[关闭]
@TryLoveCatch 2022-05-07T02:12:55.000000Z 字数 24043 阅读 1637

Android知识体系之测量(Measure)

Android知识体系


  这篇文章,主要介绍一下自定义View和自定义ViewGroup中的onMeasure用法,下面进入正题。

引子

我们举个例子:

一个简单的自定义View

  1. public class ImgView extends View {
  2. private Bitmap mBitmap;// 位图对象
  3. public ImgView(Context context, AttributeSet attrs) {
  4. super(context, attrs);
  5. }
  6. @Override
  7. protected void onDraw(Canvas canvas) {
  8. // 绘制位图
  9. canvas.drawBitmap(mBitmap, 0, 0, null);
  10. }
  11. @Override
  12. protected void onMeasure(int widthMeasureSpec,
  13. int heightMeasureSpec) {
  14. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  15. }
  16. /**
  17. * 设置位图
  18. *
  19. * @param bitmap
  20. * 位图对象
  21. */
  22. public void setBitmap(Bitmap bitmap) {
  23. this.mBitmap = bitmap;
  24. }
  25. }
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:background="#FFFFFFFF"
  5. android:orientation="vertical" >
  6. <com.test.views.ImgView
  7. android:id="@+id/main_pv"
  8. android:layout_width="match_parent"
  9. android:layout_height="match_parent" />
  10. <Button
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="AigeStudio" />
  14. <TextView
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="AigeStudio" />
  18. </LinearLayout>

  这个例子运行后,我们会发现,无论ImgView的width、height是match_parent,还是wrap_content,button和textview都不会显示在屏幕上。这个就跟view的测量机制有关系了。

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec,
  3. int heightMeasureSpec) {
  4. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  5. }

  如果自定义一个View,onMeasure方法默认就是上面这种写法,直接将参数传给父类view,此方法中的两个参数是谁传过来的呢?答案,都是父布局传过来,这个例子中是由LinearLayout传过来的,那么LinearLayout里面的又是谁传进来的呢?这里我们就需要知道根布局这个概念了。

根布局

  1. @Override
  2. public void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. }

  setContentView是我们会在自己写的Activity里面调用的,而在Activity源码里面

  1. public void setContentView(int layoutResID) {
  2. getWindow().setContentView(layoutResID);
  3. initActionBar();
  4. }

  getWindow()会返回一个继承Window的PhoneWindow(TV的话,会是TVWindow),然后执行它的setContentView(),而如下所示,PhoneWindow是在Activity的attach()中通过makeNewWindow生成的

  1. final void attach(Context context, ActivityThread aThread,
  2. // 此处省去一些代码……
  3. mWindow = PolicyManager.makeNewWindow(this);
  4. mWindow.setCallback(this);
  5. mWindow.getLayoutInflater().setPrivateFactory(this);
  6. if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
  7. mWindow.setSoftInputMode(info.softInputMode);
  8. }
  9. if (info.uiOptions != 0) {
  10. mWindow.setUiOptions(info.uiOptions);
  11. }
  12. // 此处省去巨量代码……
  13. }

  PolicyManager通过反射得到了Policy,如下

  1. public final class PolicyManager {
  2. private static final String POLICY_IMPL_CLASS_NAME =
  3. "com.android.internal.policy.impl.Policy";
  4. private static final IPolicy sPolicy;
  5. static {
  6. try {
  7. Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
  8. sPolicy = (IPolicy)policyClass.newInstance();
  9. } catch (ClassNotFoundException ex) {
  10. throw new RuntimeException(
  11. POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);
  12. } catch (InstantiationException ex) {
  13. throw new RuntimeException(
  14. POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
  15. } catch (IllegalAccessException ex) {
  16. throw new RuntimeException(
  17. POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
  18. }
  19. }
  20. // 省去构造方法……
  21. public static Window makeNewWindow(Context context) {
  22. return sPolicy.makeNewWindow(context);
  23. }
  24. // 省去无关代码……
  25. }

在Policy中的makeNewWindow()直接返回了一个PhoneWindow

  1. public Window makeNewWindow(Context context) {
  2. return new PhoneWindow(context);
  3. }

下面就说到了,上面提的setContentView()

  1. public class PhoneWindow extends Window implements MenuBuilder.Callback {
  2. // 省去代码……
  3. @Override
  4. public void setContentView(int layoutResID) {
  5. if (mContentParent == null) {
  6. installDecor();
  7. } else {
  8. mContentParent.removeAllViews();
  9. }
  10. mLayoutInflater.inflate(layoutResID, mContentParent);
  11. final Callback cb = getCallback();
  12. if (cb != null && !isDestroyed()) {
  13. cb.onContentChanged();
  14. }
  15. }
  16. // 省去代码……
  17. }

这个源码,我们可以看出来,就是将我们自己传进来的layoutId,添加到mContentParent下面,而这个mContentParent是在installDecor()里面赋值的,首先会初始化成员变量DecorView类的mDecor,然后调用generateLayout(),传入DecorView,来得到mContentParent。

  1. private void installDecor() {
  2. if (mDecor == null) {
  3. mDecor = generateDecor();
  4. // 省省省……
  5. }
  6. if (mContentParent == null) {
  7. mContentParent = generateLayout(mDecor);
  8. // 省省省……
  9. }
  10. // 省省省……
  11. }
  1. protected ViewGroup generateLayout(DecorView decor) {
  2. // 省去巨量代码……
  3. ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
  4. // 省去一些代码……
  5. }

在generateLayout()中,会根据不同的Style类型来选择不同的布局文件,然后会add进DecorView中,然后调用findViewById()从DecorView里面得到mContentParent,这个才是真正的根布局,一般情况下,根布局都是FrameLayout来担任,我们可以用xml的最顶层viewGroup调用getParent(),返回的就是FrameLayout对象,其id是android:id="@android:id/content"。

所以,一个Activity,里面是PhoneWindow,然后是DecorView,这个DecorView继承自FrameLayout,最后,才是我们自己setContentView的布局

VSYNC

接下来,View就显示出来了么?我们熟知的 onMeasure、onLayout 和 onDraw都还没有调用呢?看起来,我们需要一个时机来触发 View 的操作。
这个就得说下垂直同步机制(VSYNC):

VSYNC 就是一种同步机制,以某种固定的频率进行同步,当其他组件收到这个同步信号时,就执行相应的操作。设想一下,如果没有这个同步机制,各个模块又怎能知道在哪个时候去执行自己的工作了? 这里可以初步地将 VSYNC 当做闹钟,每间隔固定时间,就响一次,其他组件听到闹铃后,就开始干活了。这个间隔的时间,与屏幕刷新频率有关,例如大多数 Android 设备的刷新频率是 60 FPS(Frame per second),一秒钟刷新60次,因而间隔时间就是 1000 / 60 = 16.667 ms。这个时间,大家是不是很熟悉了?看过太多性能优化的文章,都说每一帧的绘制时间不要超过 16 ms,其背后的原因就是这个。绘制每一帧对应的 View,这个步骤发生在 UI 线程上,所以也不要在 UI 线程上进行耗时的操作,否则就可能在 16 ms内,无法完成界面更新操作了。

长话短说,总结一下,当 Choreographer 接收到 VSYNC 信号后,ViewRootImpl 调用 scheduleTraversals 方法,通知 View 进行相应的渲染,其后 ViewRootImpl 将 View 添加或更新到 Window 上去,并会执行TraversalRunnable 的doTraversal(),会调用到 performTraversals(),这是一个非常长的方法,里面就会提到我们熟悉的Measure、Layout 和 Draw。

Measure

MeasureSpec

下面会用到MeasureSpec,我们提前介绍下

MeasureSpec 是什么,这里是利用了位运算,将一个 int 类型包含了两种信息,分别是 size 和 mode。java 的 int 类型,可以表示 32 位数字,最高的两位数字用来表示 mode,其余的部分用来表示 size。对于手机屏幕而言,size 一般都有限,不用担心需要 31 位数字来表达 size 的情况。

MeasureSpec 分别有三种 mode,分别是 UNSPECIFIED, EXACTLY 和 AT_MOST.

  1. public static final int UNSPECIFIED = 0 << MODE_SHIFT;
  2. public static final int EXACTLY = 1 << MODE_SHIFT;
  3. public static final int AT_MOST = 2 << MODE_SHIFT;

UNSPECIFIED: 标明自身对 View 大小没有任何限制,需要子 View 的信息来帮助协定

EXACTLY: View 已经确定自身的大小

AT_MOST: 父 View 已经限定了最大大小,具体 View 能不能超过这个限制,得看不同 View 的实现情况。

而对于 Size 而言,就是具体的数值大小了。Android 提供了生成 MeasureSpec 的静态方法。

  1. public static int makeMeasureSpec(int size, int mode) {
  2. if (sUseBrokenMakeMeasureSpec) {
  3. return size + mode;
  4. } else {
  5. return (size & ~MODE_MASK) | (mode & MODE_MASK);
  6. }
  7. }

根布局的MeasureSpec

  1. private void performTraversals() {
  2. // ………省略宇宙尘埃数量那么多的代码………
  3. if (!mStopped) {
  4. // ……省略一些代码
  5. int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
  6. int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
  7. // ……省省省
  8. performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
  9. }
  10. // ………省略人体细胞数量那么多的代码………
  11. }
  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. }

从上面代码可以看出来,DecorView的大小,取决于Window的大小和WindowManager.LayoutParams,接下来看看 windowSize, rootDimension 是怎么赋值的

  1. public LayoutParams() {
  2. super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
  3. type = TYPE_APPLICATION;
  4. format = PixelFormat.OPAQUE;
  5. }

其中lp.width和lp.height均为MATCH_PARENT,其在mWindowAttributes(WindowManager.LayoutParams类型)将值赋予给lp时就已被确定,mWidth和mHeight表示当前窗口的大小,其值由performTraversals中一系列逻辑计算确定。
所以就是,window 的 LayoutParams 就是 MATCH_PARENT, 这样 DecorView 的大小就是 Window 的大小,也就是必定是全屏的。

接着看最开始代码中 performMeasure 的实现。

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

代码终于执行到measure()了

measure()和onMeasure()

  1. public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
  2. // Suppress sign extension for the low bytes
  3. long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
  4. if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
  5. widthMeasureSpec != mOldWidthMeasureSpec ||
  6. heightMeasureSpec != mOldHeightMeasureSpec) {
  7. int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
  8. mMeasureCache.indexOfKey(key);
  9. if (cacheIndex < 0 || sIgnoreMeasureCache) {
  10. // measure ourselves, this should set the measured dimension flag back
  11. onMeasure(widthMeasureSpec, heightMeasureSpec);
  12. mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
  13. }
  14. // flag not set, setMeasuredDimension() was not invoked, we raise
  15. // an exception to warn the developer
  16. if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
  17. throw new IllegalStateException("View with id " + getId() + ": "
  18. + getClass().getName() + "#onMeasure() did not set the"
  19. + " measured dimension by calling"
  20. + " setMeasuredDimension()");
  21. }
  22. mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
  23. }
  24. }

我们可以看到measure()是final方法,因为这个measure是view的重要流程,所以不能复写,代码中调用了onMeasure(),这个方法中,一定要指定MeasureSpec,不然就不知道view的大小了。

默认的onMeasure实现

  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  2. setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
  3. getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
  4. }
  5. protected int getSuggestedMinimumWidth() {
  6. return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
  7. }
  8. public static int getDefaultSize(int size, int measureSpec) {
  9. int result = size;
  10. int specMode = MeasureSpec.getMode(measureSpec);
  11. int specSize = MeasureSpec.getSize(measureSpec);
  12. switch (specMode) {
  13. case MeasureSpec.UNSPECIFIED:
  14. result = size;
  15. break;
  16. case MeasureSpec.AT_MOST:
  17. case MeasureSpec.EXACTLY:
  18. result = specSize;
  19. break;
  20. }
  21. return result;
  22. }

getSuggestedMinimumWidth(),如果背景为空,那么我们直接返回mMinWidth最小宽度,否则,就在mMinWidth和背景最小宽度之间取一个最大值,getSuggestedMinimumHeight类同,mMinWidth和mMinHeight我没记错的话应该都是100px。
getDefaultSize()中,当模式为AT_MOST和EXACTLY时均会返回解算出的测量尺寸,也就是说,上面我们说的PhoneWindow、DecorView么从它们那里获取到的测量规格层层传递到我们的自定义View中,这也解释了文章一开始那个例子,为什么我们的View在默认情况下不管是math_parent还是warp_content都能占满父容器的剩余空间。

自定义View的onMeasure

所以,我们可以自己重写onMeasure实现自己的测量逻辑,修改我们ImgView中的onMeasure():

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. // 设置测量尺寸
  4. setMeasuredDimension(250, 250);
  5. }

简单粗暴的直接设置长宽都为250px,当然,这样不好,用Android官方的话来说就是太过“专政”,因为它完全摒弃了父容器的意愿,完全由自己决定了大小。

这个时候就需要上面说的MeasureSpec了,根据它的mode来判断,父容器的意图。再次修改我们的onMeasure():

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. // 声明一个临时变量来存储计算出的测量值
  4. int resultWidth = 0;
  5. // 获取宽度测量规格中的mode
  6. int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
  7. // 获取宽度测量规格中的size
  8. int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
  9. /*
  10. * 如果爹心里有数
  11. */
  12. if (modeWidth == MeasureSpec.EXACTLY) {
  13. // 那么儿子也不要让爹难做就取爹给的大小吧
  14. resultWidth = sizeWidth;
  15. }
  16. /*
  17. * 如果爹心里没数
  18. */
  19. else {
  20. // 那么儿子可要自己看看自己需要多大了
  21. resultWidth = mBitmap.getWidth();
  22. /*
  23. * 如果爹给儿子的是一个限制值
  24. */
  25. if (modeWidth == MeasureSpec.AT_MOST) {
  26. // 那么儿子自己的需求就要跟爹的限制比比看谁小要谁
  27. resultWidth = Math.min(resultWidth, sizeWidth);
  28. }
  29. }
  30. // 设置测量尺寸
  31. setMeasuredDimension(resultWidth, resultHeight);
  32. }

我们从父容器传来的MeasureSpec中分离出了mode和size,size只是一个期望值,我们需要根据mode来计算最终的size,如果父容器对子元素没有一个确切的大小,那么我们就需要尝试去计算我们自定义View的大小,而这部分大小,更多的是由我们,也就是开发者,去根据实际情况计算的,这里我们模拟的是一个显示图片的控件,那么控件的实际大小就应该跟我们的图片一致,即使我们可以做出一定的决定,也必须要考虑父容器的限制值,当mode为AT_MOST时,size则是父容器给予我们的一个最大值,我们控件的大小就不应该超过这个值。

自定义View的padding

如上所说,控件的实际大小需要根据我们的实际需求去计算,这里我更改一下xml为我们的ImgView加一个内边距值:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:background="#FFFFFFFF"
  5. android:orientation="vertical" >
  6. <com.aigestudio.customviewdemo.views.ImgView
  7. android:id="@+id/main_pv"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:padding="20dp" />
  11. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="AigeStudio" />
  15. <TextView
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:text="AigeStudio" />
  19. </LinearLayout>

这时候运行,我们会发现,图片毫无内边距效果,因为我们的宽高,并没有考虑内边距的大小,所以予以修改:

  1. resultWidth = mBitmap.getWidth() + getPaddingLeft() + getPaddingRight();
  2. resultHeight = mBitmap.getHeight() + getPaddingTop() + getPaddingBottom();

但是,你运行之后,会发现,左右可以了,但是上下没有边距,这个是因为我们drawBitmap的时候没有考虑边距:

  1. @Override
  2. protected void onDraw(Canvas canvas) {
  3. // 绘制位图
  4. canvas.drawBitmap(mBitmap, getPaddingLeft(), getPaddingTop(), null);
  5. }

运行一下,完美,哈哈哈。

自定义View的margin

一句话,外边距轮不到view来算,Andorid将其封装在LayoutParams内交由父容器统一处理。

父容器

ViewGroup继承自View,没有重写onMeasure(),只是提供了几个方法供子类实现,但是在在子类里面(例如LinearLayout)都重写了onMeasure(),并调用了父类提供的这几个方法。

measureChildren

measureChildren 对所有可见 view 调用 measureChild 方法。

  1. protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
  2. final int size = mChildrenCount;
  3. final View[] children = mChildren;
  4. for (int i = 0; i < size; ++i) {
  5. final View child = children[i];
  6. if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
  7. measureChild(child, widthMeasureSpec, heightMeasureSpec);
  8. }
  9. }
  10. }

measureChildWithMargins

measureChildWithMargins要求 child 进行 Measure,在绘制的时候将自己的 padding 和 margins 考虑进去。经过 Measure 过后,可以得到对应的 LayoutParams 这个方法要求 child 必须得是 MarginLayoutParams,大部分的容器 View (LinearLayout、FrameLayout等等)都是这个 MarginLayoutParams。

  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. }

measureChild

measureChild 这个方法与前面这个是相对的,不同之处在于只考虑自身的 padding,不考虑 margin。

  1. protected void measureChild(View child, int parentWidthMeasureSpec,
  2. int parentHeightMeasureSpec) {
  3. // 获取子元素的布局参数
  4. final LayoutParams lp = child.getLayoutParams();
  5. /*
  6. * 将父容器的测量规格已经上下和左右的边距还有子元素本身的布局参数传入getChildMeasureSpec方法计算最终测量规格
  7. */
  8. final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
  9. mPaddingLeft + mPaddingRight, lp.width);
  10. final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
  11. mPaddingTop + mPaddingBottom, lp.height);
  12. // 调用子元素的measure传入计算好的测量规格
  13. child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
  14. }

getChildMeasureSpec,非常重要的方法

getChildMeasureSpec 这个是上述方法都会调用的方法,分别有三个参数,父view的measureSpec, 父view 的 padding(或者加上margin), 子 view 期望的大小(不一定会实现)。 方法根据特定的规则来返回对应的 MeasureSpec,这是非常重要的一个方法。

  1. public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
  2. // 获取父容器的测量模式和尺寸大小
  3. int specMode = MeasureSpec.getMode(spec);
  4. int specSize = MeasureSpec.getSize(spec);
  5. // 这个尺寸应该减去内边距的值
  6. int size = Math.max(0, specSize - padding);
  7. // 声明临时变量存值
  8. int resultSize = 0;
  9. int resultMode = 0;
  10. /*
  11. * 根据模式判断
  12. */
  13. switch (specMode) {
  14. case MeasureSpec.EXACTLY: // 父容器尺寸大小是一个确定的值
  15. /*
  16. * 根据子元素的布局参数判断
  17. */
  18. if (childDimension >= 0) { //如果childDimension是一个具体的值
  19. // 那么就将该值作为结果
  20. resultSize = childDimension;
  21. // 而这个值也是被确定的
  22. resultMode = MeasureSpec.EXACTLY;
  23. } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT
  24. // 那么就将父容器的大小作为结果
  25. resultSize = size;
  26. // 因为父容器的大小是被确定的所以子元素大小也是可以被确定的
  27. resultMode = MeasureSpec.EXACTLY;
  28. } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT
  29. // 那么就将父容器的大小作为结果
  30. resultSize = size;
  31. // 但是子元素的大小包裹了其内容后不能超过父容器
  32. resultMode = MeasureSpec.AT_MOST;
  33. }
  34. break;
  35. case MeasureSpec.AT_MOST: // 父容器尺寸大小拥有一个限制值
  36. /*
  37. * 根据子元素的布局参数判断
  38. */
  39. if (childDimension >= 0) { //如果childDimension是一个具体的值
  40. // 那么就将该值作为结果
  41. resultSize = childDimension;
  42. // 而这个值也是被确定的
  43. resultMode = MeasureSpec.EXACTLY;
  44. } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT
  45. // 那么就将父容器的大小作为结果
  46. resultSize = size;
  47. // 因为父容器的大小是受到限制值的限制所以子元素的大小也应该受到父容器的限制
  48. resultMode = MeasureSpec.AT_MOST;
  49. } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT
  50. // 那么就将父容器的大小作为结果
  51. resultSize = size;
  52. // 但是子元素的大小包裹了其内容后不能超过父容器
  53. resultMode = MeasureSpec.AT_MOST;
  54. }
  55. break;
  56. case MeasureSpec.UNSPECIFIED: // 父容器尺寸大小未受限制
  57. /*
  58. * 根据子元素的布局参数判断
  59. */
  60. if (childDimension >= 0) { //如果childDimension是一个具体的值
  61. // 那么就将该值作为结果
  62. resultSize = childDimension;
  63. // 而这个值也是被确定的
  64. resultMode = MeasureSpec.EXACTLY;
  65. } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT
  66. // 因为父容器的大小不受限制而对子元素来说也可以是任意大小所以不指定也不限制子元素的大小
  67. resultSize = 0;
  68. resultMode = MeasureSpec.UNSPECIFIED;
  69. } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT
  70. // 因为父容器的大小不受限制而对子元素来说也可以是任意大小所以不指定也不限制子元素的大小
  71. resultSize = 0;
  72. resultMode = MeasureSpec.UNSPECIFIED;
  73. }
  74. break;
  75. }
  76. // 返回封装后的测量规格
  77. return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
  78. }

上面的代码,更直观点就如下图:
img
通过上面这几个方法,我们知道,父View会根据自身的measureSpec和子View的LayoutParams来确定子View期望的measureSpec,并传到子View的measure()

自定义ViewGroup

我们自定义view的时候,最外层是一个LinearLayout,我们现在来自己实现一个简单的LinearLayout。

  1. public class CustomLayout extends ViewGroup {
  2. public CustomLayout(Context context, AttributeSet attrs) {
  3. super(context, attrs);
  4. }
  5. @Override
  6. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  7. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  8. /*
  9. * 如果有子元素
  10. */
  11. if (getChildCount() > 0) {
  12. // 那么对子元素进行测量
  13. measureChildren(widthMeasureSpec, heightMeasureSpec);
  14. }
  15. }
  16. @Override
  17. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  18. /*
  19. * 如果有子元素
  20. */
  21. if (getChildCount() > 0) {
  22. // 声明一个临时变量存储高度倍增值
  23. int mutilHeight = 0;
  24. // 那么遍历子元素并对其进行定位布局
  25. for (int i = 0; i < getChildCount(); i++) {
  26. // 获取一个子元素
  27. View child = getChildAt(i);
  28. // 通知子元素进行布局
  29. child.layout(0, mutilHeight, child.getMeasuredWidth(),
  30. child.getMeasuredHeight() + mutilHeight);
  31. // 改变高度倍增值
  32. mutilHeight += child.getMeasuredHeight();
  33. }
  34. }
  35. }
  36. }
  1. <com.test.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:background="#FFFFFFFF"
  5. android:orientation="vertical" >
  6. <com.test.views.ImgView
  7. android:id="@+id/main_pv"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:padding="50dp" />
  11. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="AigeStudio" />
  15. <TextView
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:text="AigeStudio" />
  19. </com.test.CustomLayout>

ViewGroup中的onLayout方法是一个抽象方法,这意味着你在继承时必须实现,onLayout的目的,是为了确定子元素在父容器中的位置,那么这个步骤,理应该由父容器来决定,而不是子元素。
可以看到,我们通过一个mutilHeight来存储高度倍增值,每一次子元素布局完后,将当前mutilHeight与当前子元素的高度相加,并在下一个子元素布局时,在高度上加上mutilHeight。

关于layout()的四个参数,如下图所示:
img

自定义ViewGroup的padding

给自定义的ViewGroup增加一个padding,如下

  1. <com.test.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:padding="60dp"
  5. android:background="#FFFFFFFF"
  6. android:orientation="vertical" >
  7. <com.test.views.ImgView
  8. android:id="@+id/main_pv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:padding="50dp" />
  12. <Button
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="AigeStudio" />
  16. <TextView
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:text="AigeStudio" />
  20. </com.test.CustomLayout>

这个时候,运行,会发现padding把我们的子View给吃了,导致子View显示不全,那么,我们在对子元素进行定位时,应该进一步考虑到父容器内边距的影响。

  1. @Override
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  3. // 获取父容器内边距
  4. int parentPaddingLeft = getPaddingLeft();
  5. int parentPaddingTop = getPaddingTop();
  6. /*
  7. * 如果有子元素
  8. */
  9. if (getChildCount() > 0) {
  10. // 声明一个临时变量存储高度倍增值
  11. int mutilHeight = 0;
  12. // 那么遍历子元素并对其进行定位布局
  13. for (int i = 0; i < getChildCount(); i++) {
  14. // 获取一个子元素
  15. View child = getChildAt(i);
  16. // 通知子元素进行布局
  17. // 此时考虑父容器内边距的影响
  18. child.layout(parentPaddingLeft, mutilHeight + parentPaddingTop,
  19. child.getMeasuredWidth() + parentPaddingLeft,
  20. child.getMeasuredHeight() + mutilHeight + parentPaddingTop);
  21. // 改变高度倍增值
  22. mutilHeight += child.getMeasuredHeight();
  23. }
  24. }
  25. }

自定义ViewGroup的Margin

既然内边距已经可以了,我们继续试试外边距,给自定义ViewGroup增加margin,如下:

  1. <com.test.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:layout_margin="30dp"
  5. android:padding="60dp"
  6. android:background="#FFFFFFFF"
  7. android:orientation="vertical" >
  8. <com.test.views.ImgView
  9. android:id="@+id/main_pv"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:padding="50dp" />
  13. <Button
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="AigeStudio" />
  17. <TextView
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="AigeStudio" />
  21. </com.test.CustomLayout>

我们运行,发现没什么问题,但是,如果我们给我们的子View配置外边距的时候,问题就出现了,不管margin设置多大,都不起任何效果。我们在上面也说过,子View的margin应该由父容器来处理,但是我们在CustomLayout里面没有做任何处理,所以我们需要修改我们的CustomLayout。
我们知道,Margin是封装在LayoutParams中,而我们在ViewGroup中介绍过一个方法measureChildWithMargins(),当时我们说过:

measureChildWithMargins要求 child 进行 Measure,在绘制的时候将自己的 padding 和 margins 考虑进去。经过 Measure 过后,可以得到对应的 LayoutParams 这个方法要求 child 必须得是 MarginLayoutParams,大部分的容器 View (LinearLayout、FrameLayout等等)都是这个 MarginLayoutParams。

也就是说,LayoutParams必须是MarginLayoutParams,大部分容器,LinearLayout、RelativeLayout、FrameLayout等等都继承了MarginLayoutParams,所以我们需要在CustomLayout里面也使用这个:

  1. public class CustomLayout extends ViewGroup {
  2. // 省略部分代码…………
  3. public static class CustomLayoutParams extends MarginLayoutParams {
  4. public CustomLayoutParams(MarginLayoutParams source) {
  5. super(source);
  6. }
  7. public CustomLayoutParams(android.view.ViewGroup.LayoutParams source) {
  8. super(source);
  9. }
  10. public CustomLayoutParams(Context c, AttributeSet attrs) {
  11. super(c, attrs);
  12. }
  13. public CustomLayoutParams(int width, int height) {
  14. super(width, height);
  15. }
  16. }
  17. /**
  18. * 生成默认的布局参数
  19. */
  20. @Override
  21. protected CustomLayoutParams generateDefaultLayoutParams() {
  22. return new CustomLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
  23. ViewGroup.LayoutParams.MATCH_PARENT);
  24. }
  25. /**
  26. * 生成布局参数
  27. * 将布局参数包装成我们的
  28. */
  29. @Override
  30. protected android.view.ViewGroup.LayoutParams
  31. generateLayoutParams(android.view.ViewGroup.LayoutParams p) {
  32. return new CustomLayoutParams(p);
  33. }
  34. /**
  35. * 生成布局参数
  36. * 从属性配置中生成我们的布局参数
  37. */
  38. @Override
  39. public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
  40. return new CustomLayoutParams(getContext(), attrs);
  41. }
  42. /**
  43. * 检查当前布局参数是否是我们定义的类型这在code声明布局参数时常常用到
  44. */
  45. @Override
  46. protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
  47. return p instanceof CustomLayoutParams;
  48. }
  49. // 省略部分代码…………
  50. }

下面,说一下这几个方法
generateDefaultLayoutParams

generateDefaultLayoutParams,生成默认布局参数,那么肯定是在没有设置的时候才会调用,在那里调用的呢?

  1. public void addView(View child, int index) {
  2. if (child == null) {
  3. throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
  4. }
  5. LayoutParams params = child.getLayoutParams();
  6. if (params == null) {
  7. params = generateDefaultLayoutParams();
  8. if (params == null) {
  9. throw new IllegalArgumentException(
  10. "generateDefaultLayoutParams() cannot return null"
  11. );
  12. }
  13. }
  14. addView(child, index, params);
  15. }

这个也解释了,我们平常在addview的时候,即使没有设置LayoutParams,依然可以显示,就是因为如果没有,会调用父容器的generateDefaultLayoutParams生成默认的LayoutParams。

generateLayoutParams

有两个重载方法,一个是在代码中主动new LayoutParams()时调用,一个是在xml里面设置的

接下来,修改改我们的onMeasure(),考虑margin

  1. @Override
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  3. // 声明临时变量存储父容器的期望值
  4. int parentDesireWidth = 0;
  5. int parentDesireHeight = 0;
  6. /*
  7. * 如果有子元素
  8. */
  9. if (getChildCount() > 0) {
  10. // 那么遍历子元素并对其进行测量
  11. for (int i = 0; i < getChildCount(); i++) {
  12. // 获取子元素
  13. View child = getChildAt(i);
  14. // 获取子元素的布局参数
  15. CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();
  16. // 测量子元素并考虑外边距
  17. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
  18. // 计算父容器的期望值
  19. parentDesireWidth += child.getMeasuredWidth() + clp.leftMargin + clp.rightMargin;
  20. parentDesireHeight += child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;
  21. }
  22. // 考虑父容器的内边距
  23. parentDesireWidth += getPaddingLeft() + getPaddingRight();
  24. parentDesireHeight += getPaddingTop() + getPaddingBottom();
  25. // 尝试比较建议最小值和期望值的大小并取大值
  26. parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());
  27. parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());
  28. }
  29. // 设置最终测量值
  30. setMeasuredDimension(
  31. resolveSize(parentDesireWidth, widthMeasureSpec),
  32. resolveSize(parentDesireHeight, heightMeasureSpec)
  33. );
  34. }
  35. @Override
  36. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  37. // 获取父容器内边距
  38. int parentPaddingLeft = getPaddingLeft();
  39. int parentPaddingTop = getPaddingTop();
  40. /*
  41. * 如果有子元素
  42. */
  43. if (getChildCount() > 0) {
  44. // 声明一个临时变量存储高度倍增值
  45. int mutilHeight = 0;
  46. // 那么遍历子元素并对其进行定位布局
  47. for (int i = 0; i < getChildCount(); i++) {
  48. // 获取一个子元素
  49. View child = getChildAt(i);
  50. CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();
  51. // 通知子元素进行布局
  52. // 此时考虑父容器内边距和子元素外边距的影响
  53. child.layout(parentPaddingLeft + clp.leftMargin,
  54. mutilHeight + parentPaddingTop + clp.topMargin,
  55. child.getMeasuredWidth() + parentPaddingLeft + clp.leftMargin,
  56. child.getMeasuredHeight() + mutilHeight + parentPaddingTop + clp.topMargin
  57. );
  58. // 改变高度倍增值
  59. mutilHeight += child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;
  60. }
  61. }
  62. }

结论


1. padding,都是自己来确定。自定义View,在onMeasure()和onDraw()来考虑padding;自定义ViewGroup,在onMeasure()(measureChild方法)和onLayout()时需要考虑使用padding。
2. margin,因为是在LayoutParams里面定义,所以都是父容器来确定。子View在自身的LayoutParams(必须为MarginLayoutParams)重设置margin,父ViewGroup在onMeasure()(measureChildWithMargins方法)和onLayout()中考虑使用margin。
3. 基于1和2,我们可以确定,子View或子ViewGroup的getMeasuredWidth()是包含自身的padding,但是不包含自身的margin的。
4. 一个Activity,里面是PhoneWindow,然后是DecorView,这个DecorView继承自FrameLayout,最后,才是我们自己setContentView的布局,window 的 LayoutParams 是 MATCH_PARENT, 这样 DecorView 的大小就是 Window 的大小,也就是必定是全屏的,然后把生成的MeasureSpec传递给我们的布局。

参考: 自定义控件其实很简单7/12
Window、PhoneWindow、DecorView和android.R.id.content
Android View 全解析(一) -- 窗口管理系统
Android View 全解析(二) -- 窗口管理系统

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注