本篇文章基于 之前的一篇判断ListView的每一个item高度
直接复用上一篇文章中的setListViewHeightBasedOnChildren方法,当初是使用gridView.getNumColumns();方法,获取gridview的列数,但是当我断点看的时候,发现值一直是-1, 而gridview中的mRequestedNumColumns字段反而是正常的, 看看gridview的源码中的setNumColumns方法,它把mRequestedNumColumns字段赋值了。
/**
* Set the number of columns in the grid
*
* @param numColumns The desired number of columns.
*
* @attr ref android.R.styleable#GridView_numColumns
*/
public void setNumColumns(int numColumns) {
if (numColumns != mRequestedNumColumns) {
mRequestedNumColumns = numColumns;
requestLayoutIfNecessary();
}
}
然后在 determineColumns中也看到了对mNumColumns的赋值。
private boolean determineColumns(int availableSpace) {
final int requestedHorizontalSpacing = mRequestedHorizontalSpacing;
final int stretchMode = mStretchMode;
final int requestedColumnWidth = mRequestedColumnWidth;
boolean didNotInitiallyFit = false;
if (mRequestedNumColumns == AUTO_FIT) {
if (requestedColumnWidth > 0) {
// Client told us to pick the number of columns
mNumColumns = (availableSpace + requestedHorizontalSpacing) /
(requestedColumnWidth + requestedHorizontalSpacing);
} else {
// Just make up a number if we don‘t have enough info
mNumColumns = 2;
}
} else {
// We picked the columns
mNumColumns = mRequestedNumColumns;
}
if (mNumColumns <= 0) {
mNumColumns = 1;
}
...省略若干行代码...
}
并且这个值就没有再改过。不知道为什么一直是-1.好吧,暂时先不管,晚上回去再看看。先把问题解决了再说。既然mRequestedNumColumns有值, 那我们直接通过反射拿到这个字段的值吧,看源码。
public static void setGridViewHeightBasedOnChildren(GridView gridView,
View... views) {
//获取对应的adapter
ListAdapter listAdapter = gridView.getAdapter();
Class<GridView> tempGridView = GridView.class; // 获得gridview这个类的class
int column = -1;
try {
Field field = tempGridView.getDeclaredField("mRequestedNumColumns"); // 获得申明的字段
field.setAccessible(true); // 设置访问权限
column = Integer.valueOf(field.get(gridView).toString()); // 获取字段的值
} catch (Exception e1) {
}
if (column == -1)
return;
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i += column) { // 这边因为一排column个,所以i
// +=
// column
View listItem = listAdapter.getView(i, null, gridView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}
try {
if (views != null) {
for (View view : views) {
view.measure(0, 0);
totalHeight += view.getMeasuredHeight();
}
}
} catch (Exception e) {
e.printStackTrace();
}
ViewGroup.LayoutParams params = gridView.getLayoutParams();
params.height = totalHeight
+ (gridView.getHeight() * (listAdapter.getCount() - 1)) + 10;
gridView.setLayoutParams(params);
}
好了,这个时候 gridview的高度就获得了。当然,我这里由于业务的需求,直接把高度重新设置到了gridview的身上, 按照自己的需求,修改就行了。
原文地址:http://blog.csdn.net/jys1115/article/details/46045211