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

文章详细解释了ListViewForScrollView的onMeasure方法中MeasureSpec的作用,以及如何影响ListView的滚动。通过MeasureSpec的测量模式和大小,展示了AndroidView测量过程中的父子控件交互机制,解答了为何ListView不能正常滚动的问题。
摘要由CSDN通过智能技术生成

int defStyle) {

super(context, attrs, defStyle);

}

@Override

/**

  • 重写该方法,达到使ListView适应ScrollView的效果

*/

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,

MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, expandSpec);

}

}

看到这段代码,小张更疑惑了:“这不就是继承的ListView么,也没什么特殊的逻辑啊,为啥它就是不能滑动呢?”

为了解决心里的疑惑,小张决定从这个ListViewForScrollView唯一重写的方法onMeasure(int widthMeasureSpec, int heightMeasureSpec)下手,看能不能发现问题。

刚开始看第一段代码,小张就犯难了,这个MeasureSpec是个什么东东?看起来不理解这个MeasureSpec是解决不了问题了,小张决定了解一下这个MeasureSpec:

关于MeasureSpec,小张想说

我们都知道,View展示在手机上,需要经历测量-绘制-布局三个流程,对应到View的代码中就是onMeasure()onDraw()onLayout()三个方法。在onMeasure()过程中,我们就需要借助MeasureSpec对View进行测量。

onMeasure()方法接受两个参数:

widthMeasureSpecheightMeasureSpec,这两个参数都是32位的int类型,由View的父控件传过来。

重点来了:View的onMeasure()方法,其实是由父控件调用,那View的大小难道就只能有父控件决定么?

其实不然。我们刚才也说了,widthMeasureSpec和heightMeasureSpec都是32位的int类型,他们的高两位表示测量模式mode,低30位表示测量大小size。 通过MeasureSpec这个静态类,我们很容易获取View的测量模式和测量大小,其中测量模式有3种:

  • 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;

总结

本文讲解了我对Android开发现状的一些看法,也许有些人会觉得我的观点不对,但我认为没有绝对的对与错,一切交给时间去证明吧!愿与各位坚守的同胞们互相学习,共同进步!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 25
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值