方案一:动态计算ListView的item总高度
动态设置ListView的高度 ,该方法必须在listview设置了adapter之后调用
public static void setListViewHeightBasedOnChildren(ListView listView) {
if(listView == null)
return;
ListAdapter 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(50, 50);//置空,注意:这里的listview的子项的最大布局必须是LinearLayout布局
totalHeight += listItem.getMeasuredHeight(); //循环得到listview的所有item高度的总和
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
方案二:重写ListView的onMeasure()方法
public class ExpandListView extends ListView {
public ExpandListView(Context context) {
super(context);
}
public ExpandListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}