/**
* 設(shè)置Listview的高度
*/
public void setListViewHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if(listAdapter ==null) {
return;
}
inttotalHeight =0;
for(inti =0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(ia,null, listView);
listItem.measure(0,0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParamsparams = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -1));
listView.setLayoutParams(params);
}
這個(gè)方法設(shè)置的item的Layout必須是帶有onMeasure()方法的控件,否則在計(jì)算的時(shí)候會(huì)報(bào)錯(cuò),建議使用LinearLayout。
第二種(自定義ListView)
@OverridepublicvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){intexpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>2,
MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);
}