Android: How does GridView auto_fit find the number of columns?
Looking at the GridView source, it is clear that setting the padding and the height on your ImageView will not help you at all. When a column width is not specified, it just chooses a preset number of columns (2):
private void determineColumns(int availableSpace) {
...
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;
}
...
The solution is to measure your column size before setting the GridView's column width. Here is a quick way to measure Views offscreen:
public int measureCellWidth( Context context, View cell )
{
// We need a fake parent
FrameLayout buffer = new FrameLayout( context );
android.widget.AbsListView.LayoutParams layoutParams = new android.widget.AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buffer.addView( cell, layoutParams);
cell.forceLayout();
cell.measure(1000, 1000);
int width = cell.getMeasuredWidth();
buffer.removeAllViews();
return width;
}
And then you just set the GridView's column width:
gridView.setColumnWidth( width );
According to the android:numColumns documentation
auto_fit
Display as many columns as possible to fill the available space.
So if you insert ImageView
s with
padding
set to zero
margin
set to zero
layout_width
set to wrap_content
layout_height
set to wrap_content
The gridView should contain the maximum possible number of children
Keep in mind Your ImageViews maybe are getting scaled (: