在加载列表之前确定ListView高度

时间:2015-04-20 08:05:05

标签: android android-listview

是否可以在屏幕上呈现之前确定ListView的高度?如果我的ListView有3个项目,并且高度仅限于这3个项目(并且ListView没有占据整个屏幕的高度),我可以在Android显示之前确定高度屏幕上的项目?

2 个答案:

答案 0 :(得分:2)

使用以下方法根据在场儿童获取和设置身高

 private static void setListViewHeightBasedOnChildren(ListView iListView) {
        ListAdapter listAdapter = iListView.getAdapter();
        if (listAdapter == null)
            return;

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(iListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, iListView);
            if (i == 0)
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, RelativeLayout.LayoutParams.WRAP_CONTENT));

            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = iListView.getLayoutParams();
        params.height = totalHeight + (iListView.getDividerHeight() * (listAdapter.getCount() - 1));
        Log.d("TAG", "ListView Height --- "+params.height);
        iListView.setLayoutParams(params);
        iListView.requestLayout();
    }

答案 1 :(得分:0)

如果你保持每件物品的高度固定,你必须自己计算身高。视图在制作之前无法返回其高度