在列表视图呈现在屏幕上之前,是否可以确定其高度?如果我的listview有3个条目,高度仅限于这3个条目(listview不占整个屏幕的高度),那么我可以在android在屏幕上显示条目之前确定高度吗?

最佳答案

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

 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();
    }

10-08 03:08