//重新计算ListView或GridView高度
public static int reSetAbsListViewHeightBasedOnChildren(AbsListView absListView) {
int totalHeight = 0;
ListAdapter listAdapter = absListView.getAdapter();
if (null == listAdapter) return 0;
if (absListView instanceof ListView) {
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, absListView);
listItem.measure(0, 0);//计算子项View的宽高
totalHeight += listItem.getMeasuredHeight();
}//end of for
totalHeight += (((ListView) absListView).getDividerHeight() * (listAdapter.getCount() - 1));
} else if (absListView instanceof GridView) {
int column = -1;
try {//getNumColumns一直是-1,mRequestedNumColumns反而有值
Field field = GridView.class.getDeclaredField("mRequestedNumColumns"); //获得申明的字段
field.setAccessible(true); //设置访问权限
column = Integer.valueOf(field.get((absListView)).toString());//获取字段的值
} catch (Exception e1) {
}
if (-1 != column) {
for (int i = 0; i < listAdapter.getCount(); i += column) {
View listItem = listAdapter.getView(i, null, absListView);
listItem.measure(0, 0);//计算子项View的宽高
totalHeight += listItem.getMeasuredHeight();
}//end of for
}//end of if
totalHeight += (((GridView) absListView).getVerticalSpacing() * (listAdapter.getCount() - 1));
}//end of else if
ViewGroup.LayoutParams params = absListView.getLayoutParams();
if (null != params) {
params.height = totalHeight;
absListView.setLayoutParams(params);
}//end of if
return totalHeight;
}