简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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