【问题标题】:How to calculate total row heights of listView in android?如何计算android中listView的总行高?
【发布时间】:2013-07-11 02:58:46
【问题描述】:

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

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: How to measure total height of ListView 但没有奏效。我怎样才能摆脱这个问题。任何人都可以解释这个解决方案吗?

【问题讨论】:

  • 你需要总高度有什么原因吗?如果您的列表很大,则此方法的性能会很差。
  • 你试过 listItem.getHeight() 了吗? developer.android.com/reference/android/view/…
  • 当您使用其他答案时,出了什么问题?
  • @Samuel 实际上我必须在列表视图中显示 cmets 列表。当行号为 15 或更多时,它不会返回实际高度,但如果行号为 1 到 5,则它工作得很好。我必须在视频视图下显示 cmets,这就是我需要这个的原因。还有其他解决办法吗?
  • @Samuel 当我的列表很大时,它不会完全符合我的要求。

标签: android listview


【解决方案1】:
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。 This page 告诉如何获取屏幕宽度。 一般来说,这只是一个示例,您可以在这里编写自己的公式。

【讨论】:

  • 其实你理解我的问题。当代码行数过多时,无法返回实际高度。现在我的问题是如何获取screenWidth、leftPadding 和rightPadding。您能否与我们分享一些代码 sn-p 来获得这三件事。感谢您的评论。
  • 你好,你帮了我很多。另一个问题是我在哪里使用这个 int widthSpec 值。
  • 您好,我解决了这个问题。感谢您的好评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多