简体   繁体   English

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

[英]Android gridlayout programmatically with colspan and rowspan

i can create a gridlayout with colspan and rowspan option by xml, but when i would like to do the same things programmatically it doesn't work, here is my code 我可以通过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 在此输入图像描述

try the following code 尝试以下代码

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM