如何计算android中listView的总行高?

and*_*ter 0 android listview

我使用此代码来获取listview行项的总高度,但它没有返回实际高度.这是使用过的代码

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();
    }
Run Code Online (Sandbox Code Playgroud)

例如:我有一个包含20行的listview,每行的高度彼此不同,假设为200,300,500.当我使用上面的代码时,它没有为我返回实际高度.我也尝试了这个答案:Android:如何测量ListView的总高度 但是没有用.我怎样才能摆脱这个问题.谁能解释这个解决方案?

fay*_*lon 6

View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
Run Code Online (Sandbox Code Playgroud)

功能的核心是这三行,它试图测量每个视图.listItem.measure(0,0)中的0等于MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)

大多数情况下,它会计算列表视图的准确高度.有一个例外,当视图内容太多并且将换行时,即有多行文本.在这种情况下,您应该指定一个准确的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)
Run Code Online (Sandbox Code Playgroud)

关于这里的公式更新

int listViewWidth = screenWidth - leftPadding - rightPadding; 
Run Code Online (Sandbox Code Playgroud)

这只是一个示例,展示如何估计listview宽度的宽度,该公式基于以下事实width of listview ? width of screen.填充是由你自己设置的,这里可能是0.此页面说明如何获得屏幕宽度.一般来说,它只是一个示例,您可以在此处编写自己的公式.