getView中返回的View必须是LinearLayout布局
public static void setListViewHeightBasedOnChildren(ListView listView){
NewsAdapter newsAdapter = (NewsAdapter) listView.getAdapter();
if (newsAdapter==null){
return;
}
int totalHeight=0;
// newsAdapter.getCount() 获取返回数据项的数目
for (int i=0;newsAdapter.getCount()>i;i++){
View listItem = newsAdapter.getView(i,null,listView);
// 计算子项View的宽高
listItem.measure(0,0);
// 统计所有子项的总高度
totalHeight+=listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight+(listView.getDividerHeight()*(newsAdapter.getCount()-1));
//getDividerHeight():获取子项间分隔符占用的高度, params.height 得到整个ListView 完整显示需要的高度
listView.setLayoutParams(params);
}
最后调用在设配器之后