一、android listView的每一个item布局高度不一样
1.获取listView的宽度
2.给item的measure设置参数是listView的宽度就可以获取到真正每一个item的高度
public void setListViewHeightBasedOnChildren(ListView listView1) {
BaseAdapter listAdapter = (BaseAdapter) listView1.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
//获取listView的宽度
ViewGroup.LayoutParams params = listView1.getLayoutParams();
int listViewWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth, View.MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView1);
//给item的measure设置参数是listView的宽度就可以获取到真正每一个item的高度
listItem.measure(widthSpec, 0);
totalHeight += listItem.getMeasuredHeight();
}
params.height = totalHeight
+ (listView1.getDividerHeight() * (listAdapter.getCount() + 1));
listView1.setLayoutParams(params);
}