I realize this question is quite old, but for people who are still encountering this exception today, I'll offer an explanation that may shed some light upon how downsizing a GridLayout works and why I believe it is/was throwing an exception for the OP.
In Short:
Child views of the GridLayout
can, after downsizing, occupy cells that are not within the GridLayout
's grid, which is causing the IllegalArgumentException mentioned by the OP. To avoid this, remove child views that will occupy cells outside of the GridLayout
's grid before actually calling setRowCount()
or setColumnCount()
. This can be done via GridLayout.removeView(aboutToBeIllegalChild);
or by wiping the entire layout using GridLayout.removeAllViews();
.
In Long:
All that calling GridLayout.setRowCount()
does, is specify a new number of rows that the layout should contain. It does not, however, mess with the child views that the GridLayout
currently contains, nor it's specified Spec
(what column(s) and row(s) the child view occupies).
What the exception is basically telling us, and the docs confirm, is that a GridLayout
does not allow any of its child views to occupy cells that are outside of the GridLayout
s grid. As an example, the layout will not allow a child view to occupy cell (5, 1)
when the grid is only 4 x 1
.
This leads us to why the original poster was successful at dynamically increasing the GridLayout
's dimensions, while being unsuccessful at decreasing it. When enlarging the dimensions, any child views that were already attached to the GridLayout
with specified cells, would still be placed in legal cells if the grid received extra rows or columns dynamically. When reducing the dimensions of the grid, child views that were placed in cells that would disappear as a consequence of removing rows or columns, would now be considered illegal.
To work around this, you must either remove those (about to be) illegal child views from its parent GridLayout
beforehand by calling GridLayout.removeView(aboutToBeIllegalChild);
or simply wipe the entire GridLayout
by calling GridLayout.removeAllViews();
.
Hope this helps!