Question

Currently I am trying to use GridView to create a list of images with a textview beneath them, the layout should fit as many of them width wise as possible.

When using GridView with:

<GridView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/gridView"
    android:numColumns="auto_fit"
    android:layout_gravity="center_horizontal|top"
    android:clickable="false"
    />

The expected behaviour would be that the columns would automatically wrap the content and fit as many items width wise as possible?

The textview inside the grid item layout are set to wrap_content except the ImageView, it has a static width of 75dip.

I am seeing the following layout with this code:

XX

XX

XX

If the column width is specifically set, I can easily get:

XXXX

XXXX

XXXX

Was it helpful?

Solution

If you set android:numColumns to auto_fit, you also need to set android:columnWidth so that the GridView is able to compute how many items can fit. The GridView will not create any item view before it knows how many of them it can fit in a row, and it will not measure the item views.

You should always be able to determine the width of your items in advance if you're using auto_fit. If you're not, it means that your items may have a different width and in that case your items will not render properly because columns in a GridView always have the same size.

OTHER TIPS

i think that what you should do is to measure the column width for gridview with

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 set it with

gridView.setColumnWidth(width);

also you should read this Android: How does GridView auto_fit find the number of columns?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top