listview嵌套只显示一个条目问题解决,高度动态计算

 public void setListViewHeightBasedOnChildren(ListView listView) {
 
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
            listItem.measure(desiredWidth, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
listItem.measure(desiredWidth, 0);
确定条目的宽度,测量即可计算出每个条目的高度。但是条目的根布局如果是relativieLayout,因为relativieLayout需要多次测量才能确定大小,导致计算不准确,linearlayout就没事。需要修改一下:

int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.EXACTLY);
listItem.measure(desiredWidth, 0);

你可能感兴趣的:(listview嵌套只显示一个条目问题解决,高度动态计算)