android - 如何在运行时获取准确的ListView高度?

标签 android listview android-listview height

我需要在运行时获得准确的 listView 高度。

当我使用下面的代码时,每个 listItem 的高度都不正确。

            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();
            }
            params.height = totalHeight + listview.getDividerHeight()* (listAdapter.getCount() -1);
            listview.setLayoutParams(params);
            listview.requestLayout();

当我使用 getChild 版本时,高度是准确的,但总计数不对...

        int total = 0;
        for (int i = 0; i < listview.getChildCount(); i++) {
            View childAt = listview.getChildAt(i);
            if (childAt == null)
                continue;

            int childH = childAt.getMeasuredHeight();
            total += childH;
        }
        int div = listview.getDividerHeight();
        total += (div * (listAdapter.getCount() - 1));

        if (params.height != total) {
            getLogger().info("setting measured buttons list to height: " + total);
            params.height = total;
            listview.requestLayout();
            ViewParent parent = listview.getParent();

你遇到过这个问题吗?

最佳答案

如果你只想找到 listView 的高度,你可以使用

listView.post(new Runnable()
{
    public void run()
    {
        listView.getHeight();
    }
});

关于android - 如何在运行时获取准确的ListView高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010300/

相关文章:

android - Android 中的自定义联系人列表

android - Android 密码管理器应用程序如何工作?

Android - 在 vi​​ewpager 中的不同 fragment 之间导航时隐藏的 FAB

android - 将 HashMap 存储在数组中,反之亦然

android - 奇怪的ListView排序

java - ListView ViewHolder 项目 subview 可见性改变

java - 向 ListView 添加更多元素 "overwrites"当前 ListView

android - 如何在 Android 上删除 ListViews 之间的行?

android - 从自定义适配器中的 ListView 中删除项目

java - Android ListView Adapter 错误调用notifyDataSetChanged,Android bug?