Android开发ScrollView嵌套ListView只显示一行出现的原因以及解决办法
发布日期:2021-06-28 21:30:26 浏览次数:2 分类:技术文章

本文共 2518 字,大约阅读时间需要 8 分钟。

首先看ScrollView中的onMeasure()方法,之所以首先找onMeasure()方法是因为肯定是测量出现了问题,在onMeasure()方法种首先调用了super.onMeasure()方法,点进去之后可以看到在夫布局的onMeasure方法种调用了

measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

measureChildWithMargins方法是ViewGroup中的一个方法,因为所有布局都是ViewGoup的子类,ScrollView也不例外,因此可以推测肯定是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的高度尺寸是Math.max(),高度模式是:UNSPECIFIED

那么再来看ListView中的onMeasure()方法,在ListView方法中有这么一个判断:

if (heightMode == MeasureSpec.UNSPECIFIED) {        heightSize = mListPadding.top + mListPadding.bottom + childHeight +                    getVerticalFadingEdgeLength() * 2;    }

到这里已经可以找到问题的关键了,ScrollView对子控件的高度模式约束为尽可能最大,导致上面这个if条件成立,那么heightSize的高度也就只有padding值加上一个childHeight的高度了,那么怎样解决这个问题呢?最直接的办法就是想办法不让上面的判断成立,让下面这个判断成立:

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

那么就可以重写ListView的onMeasure()方法

public class MyListView extends ListView {    public MyListView(Context context) {        super(context);    }    public MyListView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        heightMeasureSpec=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}

 

 

转载地址:https://blog.csdn.net/yaoyaoyao_123/article/details/98472136 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android开发侧滑效果的实现
下一篇:android开发ACTION_CANCEL在什么情况下出现

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月10日 07时46分59秒