// This listener is used to get the final width of the GridView and then calculate the // number of columns and the width of each column. The width of each column is variable // as the GridView has stretchMode=columnWidth. The column width is used to set the height // of each view so we get nice square thumbnails.
mGridView.getViewTreeObserver().addOnGlobalLayoutListener( //view 布局完成时调用,每次view改变时都会调用 new ViewTreeObserver.OnGlobalLayoutListener() {
@OverridepublicvoidonGlobalLayout() {
if (mAdapter.getNumColumns() == 0) {
finalint numColumns = (int) Math.floor(
mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
finalint columnWidth =
(mGridView.getWidth() / numColumns) - mImageThumbSpacing;
mAdapter.setNumColumns(numColumns); //设置 列数
mAdapter.setItemHeight(columnWidth); //设置 高度
}
}
}
});