注意,如果listitem里面有textview的话,就当一行处理进行截取数字。
public static void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
WeiboContentAdapter listAdapter = (WeiboContentAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Align.LEFT);
LinearLayout listItem;
TextView tvContent;
int totalHeight = 0;
int lineCount = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
listItem = (LinearLayout)listAdapter.getView(i, null, listView);
tvContent = (TextView) listItem.findViewById(R.id.tv_weibo_detail_content);
lineCount = getLineCount(mPaint, ((SpannedString) tvContent.getText()).toString());
tvContent.measure(0, 0); // 计算子项View 的宽高
totalHeight += tvContent.getMeasuredHeight()*lineCount + 60; // 统计所有子项的总高度
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) ;
// listView.getDividerHeight()获取子项间分隔符占用的高度
// params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}
private static int getLineCount(Paint mPaint, String content) {
int index;
int count = 0;
while(content.length() > 0){
index = mPaint.breakText(content, true, ResolutionUtil.getWPx()/2, null);
content = content.substring(index);
count++;
}
return count;
}
/**
* 动态改变listView的高度
* @param pull
*/
private void setPullLvHeight(ListView pull){
int totalHeight = 0;
for (int i = 0, len = adapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
View listItem = adapter.getView(i, null, pull);
listItem.measure(0, 0); //计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度
}
ViewGroup.LayoutParams params = pull.getLayoutParams();
params.height = totalHeight + (pull.getDividerHeight() * (pull.getCount() - 1));
pull.setLayoutParams(params);
}