美文网首页
ScrollView嵌套ListView显示不全

ScrollView嵌套ListView显示不全

作者: Noblel | 来源:发表于2017-12-13 10:58 被阅读0次

在ListView中的onMeasure方法中有这么一段代码,我们只需要关注高度就行。

    if (heightMode == MeasureSpec.UNSPECIFIED) {
        //这里只有一个childHeight,所以问题可能出在这里
        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);
    }

可以看到模式大概是UNSPECIFIED,因为heightSize = 后面只有一个childHeight(猜测)

验证?

ScrollView的onMeasure方法super的onMeasure也就是调用FrameLayout的onMeasure方法

    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            maxWidth = Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
            maxHeight = Math.max(maxHeight,
                    child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
            childState = combineMeasuredStates(childState, child.getMeasuredState());
            if (measureMatchParentChildren) {
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

调用了measureChildWithMargins方法,所以ScrollView中肯定重写了此方法进行测量

final int childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
        Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal),
        MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

可以看到此时的模式给的就是UNSPECIFIED,child.measure(childWidthMeasureSpec, childHeightMeasureSpec)最终会调用onMeasure方法

所以我们想让他进入到AT_MOST模式的循环,把最大高度设置进去。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //Integer.MAX_VALUE >> 2是表示30位的最大值,控件大小最大不能超过此大小
    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, expandSpec);
}

相关文章

网友评论

      本文标题:ScrollView嵌套ListView显示不全

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