Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decreasing row/column count of gridlayout in android

I need a dynamic gridlayout that can be toggled between 3 by 3 and 4 by 4. I can setRowCount and setColumnCount from 3 to 4 but not from 4 to 3. It will display following issue:

Caused by: java.lang.IllegalArgumentException: rowCount must be greater than or equal to the maximum of all grid indices (and spans) defined in the LayoutParams of each child.

Is there any work around to achieve this using gridlayout?

like image 713
Dewa Manandhar Avatar asked Oct 22 '14 18:10

Dewa Manandhar


People also ask

Is GridLayout deprecated?

GridLayout is also not deprecated.

How do I change GridLayout size?

While you can't make components span multiple rows with GridLayout, you can resize them all uniformly. Put your GridLayout on its own JPanel, and then you can use panel. setSize(x,y) to change the panel size and thus increase or decrease the size of the cells.

What is the difference between GridLayout and GridView in Android?

Let us not get confused with GridView and GridLayout to be the same. GridView simply gives us a two-dimensional view to display the items on the screen, under ViewGroup. On the other hand, GridLayout is a layout manager that arranges the views in a grid.

What method do we use to set the number of rows in a GridLayout?

getSize(size); int width = size. x; This code creates a GridLayout within the current context and sets its number of rows to four and its number of columns to two.


1 Answers

Based on Teun Kooijman answer you can just change Spec in GridLayout.LayoutParams and keep all Views inside the GridLayout:

private void changeColumnCount(int columnCount) {
        if (gridLayout.getColumnCount() != columnCount) {
            final int viewsCount = gridLayout.getChildCount();
            for (int i = 0; i < viewsCount; i++) {
                View view = gridLayout.getChildAt(i);
                //new GridLayout.LayoutParams created with Spec.UNSPECIFIED
                //which are package visible
                view.setLayoutParams(new GridLayout.LayoutParams());
            }
            gridLayout.setColumnCount(columnCount);
        }
    }

You can also change Spec in other way by accessing GridLayout.LayoutParams.rowSpec and GridLayout.LayoutParams.columnSpec

like image 141
Hensin Avatar answered Oct 02 '22 23:10

Hensin