gridview.getNumColumns()列数获取得到-1 所以列数写死为2
public void setGridViewHeight(GridView gridview) {
// 获取gridview的adapter
ListAdapter listAdapter = gridview.getAdapter();
if (listAdapter == null) {
return;
}
// 固定列宽,有多少列
//int numColumns= gridview.getNumColumns(); //5
int numColumns = 2;
View listItem = listAdapter.getView(0, null, gridview);
listItem.measure(0, 0);
// 获取item的高度和
int totalHeight = listItem.getMeasuredHeight();
// 获取布局参数
ViewGroup.LayoutParams params = gridview.getLayoutParams();
if (listAdapter.getCount() % numColumns != 0) {
totalHeight = totalHeight * (listAdapter.getCount() / numColumns + 1);
} else {
totalHeight = totalHeight * (listAdapter.getCount() / numColumns);
}
// 设置高度
params.height = totalHeight;
// 设置margin
//((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
// 设置参数
gridview.setLayoutParams(params);
}