Set rowSpan or colSpan of a child of a GridLayout programmatically?
You could modify GridLayout layout_rowSpan attribute like this:
// View allocated in first row and first column
View child = findViewById(R.id.row0column0);
GridLayout.LayoutParams params =
new GridLayout.LayoutParams(child.getLayoutParams());
params.rowSpec = GridLayout.spec(0, 2); // First cell in first row use rowSpan 2.
params.columnSpec = GridLayout.spec(0, 2); // First cell in first column use columnSpan 2.
child.setLayoutParams(params);
I agree documentation needs a little bit improvement in this regard.
How about this?
GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
layoutParams.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, item.getRowSpan());
layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, item.getColumnSpan());
According to documentation, you should also call setLayoutParams on GridLayout IF you change column or row span AFTER the child views are inserted into GridLayout. You don't need this if you add them while setting span
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);
}