0

我使用此代码获取列表视图行项目的总高度,但它没有返回实际高度。这是使用的代码

public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

例如:我有一个有 20 行的列表视图,每行高度彼此不同,假设为 200,300,500。当我使用上面的代码时,它没有为我返回实际高度。我也试过这个答案:Android:如何测量 ListView 的总高度 但没有用。我怎样才能摆脱这个问题。任何人都可以解释这个解决方案吗?

4

1 回答 1

6
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();

函数的核心就是这三行,它试图衡量每一个视图。listItem.measure(0, 0) 中的 0 等于MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)

大多数情况下,它将计算列表视图的准确高度。有一个例外,当视图内容太多并且会换行时,即有很多行文本。在这种情况下,您应该为 measure() 指定准确的 widthSpec。所以listItem.measure(0, 0)改为

// try to give a estimated width of listview
int listViewWidth = screenWidth - leftPadding - rightPadding; 
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth, MeasureSpec.AT_MOST);
listItem.measure(listViewWidth, 0)

更新关于这里的公式

int listViewWidth = screenWidth - leftPadding - rightPadding; 

这只是一个例子来说明如何估计listview的宽度,公式是基于width of listview ≈ width of screen. 填充由您自己设置,此处可能为 0。本页介绍如何获取屏幕宽度。一般来说,这只是一个示例,您可以在这里编写自己的公式。

于 2013-07-12T14:41:31.527 回答