How to configure ListView to automatically change its height?

前端 未结 5 1650
梦毁少年i
梦毁少年i 2021-01-03 04:50

I have three ListView widgets in the same LinearLayout. Something like this (I\'m omitting XML elements that are not relevant in this example):

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 05:38

    Instead of editing my previous answer, here's my actual version (after finally the case became the issue and I had to fix it)

        @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0));
    
        int childHeight = getMeasuredHeight() - (getListPaddingTop() + getListPaddingBottom() +  getVerticalFadingEdgeLength() * 2);
    
        // on a first run let's have a space for at least one child so it'll trigger remeasurement
        int fullHeight = getListPaddingTop() + getListPaddingBottom() + childHeight*(getCount());
    
        int newChildHeight = 0;
        for (int x = 0; x

    The trickiest part is that the onMeasure gets called twice, first for approx layout and then after items added for a precise one and both have to return sane results.

提交回复
热议问题