NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10859

How to set number of columns in GridView according to minimal and maximal column width?

I have a GridView in my layout that should take up as much space as available (all other elements of the layout have a fixed size).

I want all the Views in the cells of the GridView to take up as much width as possible, i.e. not leaving any additional space except the spacing defined by the GridView.

I want the number of columns of the GridViewto be automatically determined by the following constraints:

For this android needs to determine the right number of columns somehow by itself (auto_fit defaults to 2 if the cell width is unknown). The problem is that my implementation of ListAdapter delivering the cell Views with getView() must deliver views of the right size before the width of the grid view is known (parent.getWidth() will return 0 initially).

So during the layout phase the width of the grid view is not yet known, but still the grid view already wants to know the number of columns. For determining the number of columns according to my constraints however I must know the width of the grid view (and since it is taking up all available space anyway this should be possible to know).

Also one can set a minimal width and height on Views but this seems not to help with column widths of a grid view.

So how can I enforce all these constraints programmatically?

Upvotes: 1

Views: 2213

Answers (1)

NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10859

In the end it was much easier than I had thought in the beginning.

Android does it more or less automatically for you, if you:

  • set android:numColumns="auto_fit" android:stretchMode="columnWidth" in the layout of the grid view and
  • set android:minWidth="200dp" in the layout of the views used for the grid view cells and
  • set android:layout_width="match_parent" android:layout_height="match_parent" in both

This means that each column must be at least 200 dp and android will determine the number of columns so that the maximal number of columns with a column width of at least 200 dp is set and if the column are wider it will stretch the cells (evenly).

I had more complicated solutions involving getViewTreeObserver().addOnGlobalLayoutListener() to wait until the grid view had determined it's size than calculating the number of columns by myself and then setting an Adapter but the solution above was identical in result and much less effort.

Upvotes: 1

Related Questions