一丶重新計(jì)算listview的高度
public 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();
int height = getWindowManager().getDefaultDisplay().getHeight();
params.height = totalHeight + (listView.getDividerHeight() *(listAdapter.getCount() - 1));
// ((MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可刪除
listView.setLayoutParams(params);
}
二丶重新計(jì)算gridview的高度
public void setGridViewHeightBasedOnChildren(GridView gridView) {
// 獲取GridView對(duì)應(yīng)的Adapter
ListAdapter listAdapter = gridView.getAdapter();
if (listAdapter == null) {
return;
}
int rows;
int columns=0;
int horizontalBorderHeight=0;
int verticalBorderHeight =0;
Class<?> clazz=gridView.getClass();
try {
//利用反射惰许,取得每行顯示的個(gè)數(shù)
Field column=clazz.getDeclaredField("mRequestedNumColumns");
column.setAccessible(true);
columns=(Integer)column.get(gridView);
//利用反射蟀伸,取得橫向分割線高度
Field horizontalSpacing=clazz.getDeclaredField("mRequestedHorizontalSpacing");
horizontalSpacing.setAccessible(true);
horizontalBorderHeight=(Integer)horizontalSpacing.get(gridView);
//利用反射匀油,取得屬豎向分割線高度
// Field verticalSpacing =clazz.getDeclaredField("mRequestedVerticalSpacing");
// verticalSpacing.setAccessible(true);
// verticalBorderHeight=(Integer)verticalSpacing.get(gridView);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//判斷數(shù)據(jù)總數(shù)除以每行個(gè)數(shù)是否整除推励。不能整除代表有多余胞谭,需要加一行
if(listAdapter.getCount()%columns>0){
rows=listAdapter.getCount()/columns+1;
}else {
rows=listAdapter.getCount()/columns;
}
int totalHeight = 0;
for (int i = 0; i < rows; i++) { //只計(jì)算每項(xiàng)高度*行數(shù)
View listItem = listAdapter.getView(i, null, gridView);
listItem.measure(0, 0); // 計(jì)算子項(xiàng)View 的寬高
totalHeight += listItem.getMeasuredHeight(); // 統(tǒng)計(jì)所有子項(xiàng)的總高度
}
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.height = totalHeight+horizontalBorderHeight*(rows-1);//最后加上分割線總高度
gridView.setLayoutParams(params);
}