1:在自定义listview中重写onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
2:动态计算
public int getMeasuredHeight() {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return 0;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View ItemView = listAdapter.getView(i, null, listView);
ItemView.measure(0, 0);
totalHeight += ItemView.getMeasuredHeight();
}
int height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
return height;
}