ScrollView嵌套ListView显示不全
2017-12-13 本文已影响0人
Noblel
在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);
}