Set rowSpan or colSpan of a child of a GridLayout programmatically?

The_Unknown picture The_Unknown · Nov 23, 2012 · Viewed 58.3k times · Source

I have a GridLayout with 5 columns and 3 rows. Now I can insert arbitrary child views, which is great. Even better is, that I can assign columnSpan=2 to some item in order to span it to 2 columns (the same with rowSpan).

The problem now is, that I cannot assign rowSpan or columnSpan programmatically (i.e. at runtime). Some search suggested something like this:

layoutParams.columnSpec = GridLayout.spec(0, columnSpan);

But I don't quite understand what the parameters of spec mean (start and size). The documentation is also quite poor at this point.

Any help is highly appreciated!

Answer

Nikhil Pingle picture Nikhil Pingle · Feb 5, 2013
    GridLayout gridLayout = (GridLayout)findViewById(R.id.tableGrid);

    gridLayout.removeAllViews();

    int total = 12;
    int column = 5;
    int row = total / column;
    gridLayout.setColumnCount(column);
    gridLayout.setRowCount(row + 1);
    for(int i =0, c = 0, r = 0; i < total; i++, c++)
    {
        if(c == column)
        {
            c = 0;
            r++;
        }
        ImageView oImageView = new ImageView(this);
        oImageView.setImageResource(R.drawable.ic_launcher);
        GridLayout.LayoutParams param =new GridLayout.LayoutParams();
        param.height = LayoutParams.WRAP_CONTENT;
        param.width = LayoutParams.WRAP_CONTENT;
        param.rightMargin = 5;
        param.topMargin = 5;
        param.setGravity(Gravity.CENTER);
        param.columnSpec = GridLayout.spec(c);
        param.rowSpec = GridLayout.spec(r);
        oImageView.setLayoutParams (param);
        gridLayout.addView(oImageView);
    }

 have look on this image - you can change number of rows and column as you need