【问题标题】:calculate total row heights of listView in android计算android中listView的总行高
【发布时间】:2014-03-13 07:24:23
【问题描述】:

我在ScrollView 中使用ListView,众所周知,它会产生问题。

我从这个网站得到了很好的解决方案:How to calculate total row heights of listView in android?

但是对于某些项目,它没有正确显示Listview。有没有改进的解决方案?

我的代码:

     public static void getListViewSize(ListView myListView, Context context) {
        ListAdapter myListAdapter = myListView.getAdapter();

        if (myListAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {

            View listItem = myListAdapter.getView(size, null, myListView);
            if (listItem instanceof ViewGroup)
                listItem.setLayoutParams(new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT));

            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            @SuppressWarnings("deprecation")
            int screenWidth = display.getWidth();
            int listViewWidth = screenWidth - 20;
            int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth,
                    MeasureSpec.AT_MOST);
            listItem.measure(widthSpec, 0);

            totalHeight += listItem.getMeasuredHeight();

            Log.e("height of listItem:", String.valueOf(totalHeight));
        }

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

【问题讨论】:

标签: android listview 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; 
enter code here

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

【讨论】:

    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多