碰到过几次同样的问题,但是今天还是做一个总结:
错误的原因是:
在布局文件中给ListView的属性增加了android:padding,那么计算ListView的高度=item的个数 x item的高度+item个数 x padding的值,这样才会正确;那如果非要在布局文件中增加该属性,那么只能根据上面给定的公式计算了。
这是重新计算ListView的高度:
/** * 重新计算listview的高度 */ private int getListViewParams(ListView listView, BaseAdapter baseAdapter) { int totalHeight = 0; for (int i = 0, len = baseAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目 View listItem = baseAdapter.getView(i, null, listView); listItem.measure(0, 0); //计算子项View 的宽高 totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度 } return totalHeight; }
实际调用中:
CommentDynamicAdapter cDynamicAdapter=new CommentDynamicAdapter(context,personalInfo.getCommentList()); viewHolder.lvDetailComment.setAdapter(cDynamicAdapter); LinearLayout.LayoutParams recordLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); if(personalInfo.getCommentList().size()>3){ recordLayoutParams.height=getListViewParams2(viewHolder.lvDetailComment, cDynamicAdapter); }else{ recordLayoutParams.height = getListViewParams(viewHolder.lvDetailComment, cDynamicAdapter); } recordLayoutParams.setMargins(20,0,0,0);//设置ListView距离屏幕左边的距离 viewHolder.lvDetailComment.setLayoutParams(recordLayoutParams);
在setAdapter之后去调用
//重新计算ListView的高度 private void setListViewItemHeight(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); }