解决办法一:自己写一个方法在设置适配器后调用
public static void setListViewHeightBasedOnChildren(ListView listView) {
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(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
设置完适配器后调用该方法,将ListView作参数传入
Utility.setListViewHeightBasedOnChildren(mListView);
解决办法二:自定义ListView重写onMeasure方法
public class NestListView extends ListView {
public NestListView(Context context) {
super(context);
}
public NestListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NestListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}