Search code examples
androidandroid-gridlayout

android – How to leave empty space in GridLayout


I have GridLayout (from support library) where are two rows of buttons. All buttons have width set to 2 and height 1. The first row should be shifted one position to the right. When I do this, the GridLayout works like the first row is not shifted.

Second row:

GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(1, 1, 1);
params.columnSpec = GridLayout.spec(x, 2, 1);

First row:

GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rowSpec = GridLayout.spec(0, 1, 1);
params.columnSpec = GridLayout.spec(x + 1, 2, 1);

Solution

  • You have to insert dummy views to all cells on top and on the left (start).

    for (int x = 0; x < gridLayout.getColumnCount(); x++) {
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.rowSpec = GridLayout.spec(0, 1, 1);
        params.columnSpec = GridLayout.spec(x, 1, 1);
        params.setGravity(Gravity.FILL);
        params.width = 0;
        gridLayout.addView(new Space(this), params);
    }
    for (int y = 0; y < gridLayout.getRowCount(); y++) {
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.rowSpec = GridLayout.spec(y, 1, 1);
        params.columnSpec = GridLayout.spec(0, 1, 1);
        params.setGravity(Gravity.FILL);
        params.width = 0;
        gridLayout.addView(new Space(this), params);
    }