當(dāng)我們使用ScrollView中嵌套ListView空間,無法正確的計算ListView的大小,故可以通過代碼,根據(jù)當(dāng)前的ListView的列表項計算列表的尺寸。實現(xiàn)代碼如下:
privatevoidsetListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();if(listAdapter ==null) {// pre-conditionreturn;
}inttotalHeight =0;for(inti =0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i,null, listView);
listItem.measure(0,0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParamsparams= listView.getLayoutParams();params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() -1));
listView.setLayoutParams(params);
}
使用該方法需要注意:子ListView的每個Item必須是LinearLayout,不能是其他的,因為其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時拋出異常。
2、 自定義ListView,重載onMeasure()方法,設(shè)置全部顯示
/**
* Integer.MAX_VALUE >> 2,如果不設(shè)置,系統(tǒng)默認(rèn)設(shè)置是顯示兩條
*/publicvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec) {intexpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>2,
MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);
}