血泪教训:因为不够了解MeasureSpec而引发的生产事故

  • UNSPECIFIED

父控件不对你有任何限制,你想要多大给你多大,想上天就上天。这种情况一般用于系统内部,表示一种测量状态。(这个模式主要用于系统内部多次Measure的情形,并不是真的说你想要多大最后就真有多大)

  • EXACTLY

父控件已经知道你所需的精确大小,你的最终大小应该就是这么大。

  • AT_MOST

你的大小不能大于父控件给你指定的size,但具体是多少,得看你自己的实现。

父控件通过ViewGroup中的静态方法getChildMeasureSpec来获取子控件的测量规格。下面是getChildMeasureSpec()的代码(由于小张terrible的英语水平,就不给大家翻译注释了,大家可以自行有道~):

/**

  • Does the hard part of measureChildren: figuring out the MeasureSpec to

  • pass to a particular child. This method figures out the right MeasureSpec

  • for one dimension (height or width) of one child view.

  • The goal is to combine information from our MeasureSpec with the

  • LayoutParams of the child to get the best possible results. For example,

  • if the this view knows its size (because its MeasureSpec has a mode of

  • EXACTLY), and the child has indicated in its LayoutParams that it wants

  • to be the same size as the parent, the parent should ask the child to

  • layout given an exact size.

  • @param spec The requirements for this view

  • @param padding The padding of this view for the current dimension and

  •    margins, if applicable
    
  • @param childDimension How big the child wants to be in the current

  •    dimension
    
  • @return a MeasureSpec integer for the child

*/

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;

}

//noinspection ResourceType

return MeasureSpec.makeMeasureSpec(resultSize, resultMode);

}

该方法通过将父控件的测量规格和childview的布局参数LayoutParams相结合,得到一个最可能符合条件的child view的测量规格。

通过以上代码,大家可以有一个概念:就是一个View的大小是由它的父控件加上自身的LayoutParams决定的。详情如下(图片来源于任玉刚博客):

解决问题

通过了解View的Measure过程,小张知道了,在ListViewForScrollView的onMeasure()方法里,强行将ListView的测量模式改为了AT_MOST,并将测量大小改为了MAX_VALUE >> 2,接着调用父类ListView的onMeasure()方法,我们来看看ListView的onMeasure()方法:

/** 源码来自8.0.0_r4,不同版本可能略有不同 **/

@Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

/** 此处省略不相关代码 **/

//…

// 测量模式为AT_MOST,测量大小为MAX_VALUE >> 2,也就是536870911

if (heightMode == MeasureSpec.AT_MOST) {

heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);

}

setMeasuredDimension(widthSize, heightSize);

/** 继续省略 **/

//…

}

通过上面的代码我们可以看到,最终这个自定义的ListViewForScrollView的高度是由measureHeightOfChildren这个方法确定的,小张接着查看这个方法:

/**

  • Measures the height of the given range of children (inclusive) and

  • returns the height with this ListView’s padding and divider heights

  • included. If maxHeight is provided, the measuring will stop when the

  • current height reaches maxHeight.

  • @param widthMeasureSpec The width measure spec to be given to a child’s

  •        {@link View#measure(int, int)}.
    
  • @param startPosition The position of the first child to be shown.

  • @param endPosition The (inclusive) position of the last child to be

  •        shown. Specify {@link #NO_POSITION} if the last child should be
    
  •        the last available child from the adapter.
    
  • @param maxHeight The maximum height that will be returned (if all the

  •        children don't fit in this value, this value will be
    
  •        returned).
    
  • @param disallowPartialChildPosition In general, whether the returned

  •        height should only contain entire children. This is more
    
  •        powerful--it is the first inclusive position at which partial
    
  •        children will not be allowed. Example: it looks nice to have
    
  •        at least 3 completely visible children, and in portrait this
    
  •        will most likely fit; but in landscape there could be times
    
  •        when even 2 children can not be completely shown, so a value
    
  •        of 2 (remember, inclusive) would be good (assuming
    
  •        startPosition is 0).
    
  • @return The height of this ListView with the given children.

*/

final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,

int maxHeight, int disallowPartialChildPosition) {

final ListAdapter adapter = mAdapter;

if (adapter == null) {

return mListPadding.top + mListPadding.bottom;

}

// Include the padding of the list

int returnedHeight = mListPadding.top + mListPadding.bottom;

final int dividerHeight = mDividerHeight;

// The previous height value that was less than maxHeight and contained

// no partial children

int prevHeightWithoutPartialChild = 0;

int i;

View child;

// mItemCount - 1 since endPosition parameter is inclusive

endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;

final AbsListView.RecycleBin recycleBin = mRecycler;

final boolean recyle = recycleOnMeasure();

final boolean[] isScrap = mIsScrap;

for (i = startPosition; i <= endPosition; ++i) {

child = obtainView(i, isScrap);

measureScrapChild(child, i, widthMeasureSpec, maxHeight);

if (i > 0) {

// Count the divider for all but one child

returnedHeight += dividerHeight;

}

// Recycle the view before we possibly return from the method

if (recyle && recycleBin.shouldRecycleViewType(

((LayoutParams) child.getLayoutParams()).viewType)) {

recycleBin.addScrapView(child, -1);

}

returnedHeight += child.getMeasuredHeight();

if (returnedHeight >= maxHeight) {

// We went over, figure out which height to return. If returnedHeight > maxHeight,

// then the i’th position did not fit completely.

return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)

&& (i > disallowPartialChildPosition) // We’ve past the min pos

&& (prevHeightWithoutPartialChild > 0) // We have a prev height

&& (returnedHeight != maxHeight) // i’th child did not fit completely

? prevHeightWithoutPartialChild
maxHeight;

}

if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {

prevHeightWithoutPartialChild = returnedHeight;

}

}

// At this point, we went through the range of children, and they each

// completely fit, so return the returnedHeight

尾声

在我的博客上很多朋友都在给我留言,需要一些系统的面试高频题目。之前说过我的复习范围无非是个人技术博客还有整理的笔记,考虑到笔记是手写版不利于保存,所以打算重新整理并放到网上,时间原因这里先列出面试问题,题解详见:


展示学习笔记

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
of children, and they each

// completely fit, so return the returnedHeight

尾声

在我的博客上很多朋友都在给我留言,需要一些系统的面试高频题目。之前说过我的复习范围无非是个人技术博客还有整理的笔记,考虑到笔记是手写版不利于保存,所以打算重新整理并放到网上,时间原因这里先列出面试问题,题解详见:

[外链图片转存中…(img-8wdvA9on-1715365955481)]
展示学习笔记
[外链图片转存中…(img-wLGIFyj2-1715365955482)]
[外链图片转存中…(img-VK33x45L-1715365955482)]

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值