阅读 456

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

夭寿啦,出生产事故了

那天,风和日丽,菜鸡Android开发工程师小张开心的写着 bug 代码 ,突然,测试经理老石跑过来说客户报上来一个线上bug,小张突然菊花一紧,说不可能,我的代码是不可能有问题的。然后老石从胯下 口袋 掏出来手机,三下五除二将bug复现出来了:

底部弹框内容被遮挡

情景再现:

从图中我们明显能看到,底部的服务弹框被裁切挡住了,显示的不完整。

分析原因:

看到复原的犯罪现场,小张心里一个放松:“还好还好,不是我写的代码。”当着老石的面,小张承认是代码出了问题,答应了老石下个版本修复,老石才不依不挠的走开了。打发走了老石,小张开始分析起来问题了。开始,小张简单的认为是底部的弹框(Dialog)的高度太小了,造成了dialog的内容显示不完整。然鹅,看到出问题的代码,小张开始发现事情并不简单,涉事代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- 省略无关代码 -->
    <com.xx.ListViewForScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="18dip"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="48dp"
        android:divider="@null">
    </com.xx.ListViewForScrollView>
</RelativeLayout>
复制代码

看到上面Dialog的布局xml文件中的ListViewForScrollView小张心里不禁泛起了嘀咕:“怎么又是自定义的View,又要看一大堆逻辑了,脑壳疼,脑壳疼...”转念一想,不对啊,这个View看名字一看就是继承自ListView,就算是Dialog的高度不够,这个ListViewForScrollView也应该能滑动才对啊,现在不能滑动了是怎么一回事,有问题有问题...

不看代码光靠猜是解决不了问题的,小张下定决心去研究研究这个自定义View,打开这个ListViewForScrollView的代码,小张松了一口气:还好还好,代码量并不多,看起来逻辑并不复杂:

public class ListViewForScrollView extends ListView {

	public ListViewForScrollView(Context context) {
		super(context);
	}

	public ListViewForScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ListViewForScrollView(Context context, AttributeSet attrs,
			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;
        }

        // 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
        return returnedHeight;
    }
复制代码

通过查看该方法,小张知道了这个方法的意义就是测量给定范围的高度,并返回包含此ListView的填充和分隔符高度的高度。如果提供了maxHeight,当当前高度达到maxHeight时,测量将停止。而对于ListViewForScrollView,maxHeight就是上面onMeasure()中我们传过来的536870911(即MAX_VALUE >> 2),如果ListView的itemView的总高度不超过这个值,那么ListView的高度就是所有itemView高度加上分隔符加上padding的高度,否则就为536870911。所以问题的原因就很清楚了,ListViewForScrollView的高度在大多数情况下都为我们指定的536870911,而这种情况下ListView是不能滑动的。

解决问题

通过研究ListViewForScrollView,小张发现这个自定义View是用来解决ScrollView嵌套ListView带来的滑动冲突等问题的,而出问题的Dialog根布局是RelativeLayout,并不是ScrollView,所以小张将布局文件中的ListViewForScrollView换成了ListView,问题圆满解决了。

吃一堑长一智

通过这次的血泪教训,小张明白了:

  1. View的绘制流程
  2. MeasureSpec的作用
  3. 使用自定义View的时候要充分理解其作用
关注下面的标签,发现更多相似文章
评论