Android gridlayout以编程方式使用colspan和rowspan

时间:2016-08-03 11:29:58

标签: android html-table

我可以用xml创建一个带有colspan和rowspan选项的gridlayout, 但是当我想以编程方式执行相同的操作时它不起作用,这是我的代码

    int column = 3;
    int row = 3;
    gridLayout.setColumnCount(column);
    gridLayout.setRowCount(row);
    Button btn1 = new Button(this);
    btn1.setBackgroundColor(Color.BLUE);
    btn1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    GridLayout.LayoutParams lParams = new GridLayout.LayoutParams(btn1.getLayoutParams());
    lParams.rowSpec = GridLayout.spec(0, 2);   
    lParams.columnSpec = GridLayout.spec(0, 3);
    gridLayout.addView(btn1,lParams);

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试以下代码

int row= 3;
int column = 3;
int row = row/ 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++;
    }
    Button btn1= new Button(this);
  //If required set image other wise leave it
    btn1.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);
    btn1.setLayoutParams (param);
    gridLayout.addView(oImageView);
}