美文网首页程序员
源码分析ScrollView嵌套ListView展示不全的问题

源码分析ScrollView嵌套ListView展示不全的问题

作者: JamFF | 来源:发表于2019-03-18 20:11 被阅读0次

解决方式网上一大把,有两种方法,一种是遍历 item,将 itme 的高度累加,另一个重写 ListView 的 onMeasure。我们这里主要说下,产生问题的原因,以及第二种解决方式的原理。

源码分析

ListView 展示不全,首先想到 ListView 的高度,高度测量是在 onMeasure 中进行的,看下源码。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Sets up mListPadding
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);// ①
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);// ②
    
    ...
    
    if (heightMode == MeasureSpec.UNSPECIFIED) {
        heightSize = mListPadding.top + mListPadding.bottom + childHeight +
                getVerticalFadingEdgeLength() * 2;// ③
    }

    if (heightMode == MeasureSpec.AT_MOST) {
        // TODO: after first layout we should maybe start at the first visible position, not 0
        heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);// ④
    }

    setMeasuredDimension(widthSize, heightSize);

    mWidthMeasureSpec = widthMeasureSpec;
}

在 onMeasure 的关键代码是 heightSize 的值,只有在②、③、④三处代码,对 heightSize 赋值进行赋值,可以大胆的猜测一下,可能在执行③的时候,ListView 出现了问题,展示一个 item 的高度,因为只加了一个 childHeight

这里介绍一下①、②代码,MeasureSpec 是测量规格,int 值,32位,前面两位当做 mode,后面 30位当做 value。①是从 MeasureSpec 取 mode,②是从 MeasureSpec 取 value。

我们先来看看④的代码。

final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
        int maxHeight, int disallowPartialChildPosition) {
    
    ...

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

这里通过遍历计算每个 child 的高度,这个才是常规的方式,更加认证了,bug 出现的原因是,ScrollView 给了一个不确定的测量规格 MeasureSpec.UNSPECIFIED,导致 ListView 在 onMeasure 的时候执行了③的代码。

继续在 ScrollView 中寻找答案。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);// ①

    if (!mFillViewport) {
        return;
    }

    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    if (heightMode == MeasureSpec.UNSPECIFIED) {
        return;
    }

    if (getChildCount() > 0) {
        final View child = getChildAt(0);// ② 解释了为什么只能嵌套一个子控件
        ...
    }
}

先说句题外话,上面②的位置解释了,ScrollView 为什么只能有一个子控件,就算有多个,也只测量一个。
关键代码在①处,父类 FrameLayout 的 onMeasure 中。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();
    ...
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
            // 关键代码
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
        ...
        }
    }
}

这里需要注意一下,点击进入的是 ViewGroup 的 measureChildWithMargins,是看不到关键代码的,需要进入 ScrollView,ScrollView 重写了 measureChildWithMargins 方法。

@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                    + widthUsed, lp.width);
    final int usedTotal = mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin +
            heightUsed;
    final int childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
            Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal),
            MeasureSpec.UNSPECIFIED);// 关键代码

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

这里就可以看到 childHeightMeasureSpec 设置了测量规格为 MeasureSpec.UNSPECIFIED,传递到 child,也就是 ListView 的 measure 方法,在 measure 又调用了 ListView 的 onMeasure,在回过头来,看文章第一段代码①处,取到的 widthMode 值就是 MeasureSpec.UNSPECIFIED,所以自然会出现 ListView 展示不全的问题。

解决方式

原因分析清楚了,大家应该还是明白,为什么重写 ListView 的 onMeasure,就可以修复该问题。

public void onMeasure() {
    // 第一个参数是value,第二个参数是mode,通过makeMeasureSpec工具类,合并为一个int
    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, expandSpec); 
}

其实 makeMeasureSpec 是 MeasureSpec 拼接 value 和 mode 的方法,mode 设置为 MeasureSpec.AT_MOST 很好理解,value 设置为 Integer.MAX_VALUE 是为了保证高度足够大,也很好理解。关键是位运算,这里就涉及到MeasureSpec的构成,MeasureSpec的前两位是mode,后面30位才是value,所以这里,value的最大值就是 Integer.MAX_VALUE >> 2 了。


我是JamFF,希望今天的文章对你有帮助。
END.


相关文章

网友评论

    本文标题:源码分析ScrollView嵌套ListView展示不全的问题

    本文链接:https://www.haomeiwen.com/subject/faspmqtx.html