问题描述:

I'm trying to add buttons in Table layout.

Initially I will have a single row with a single button.

When the user clicks that button, It should create 2 dynamic buttons in the next row 'Horizontally'.

But with my code, I'm getting vertically dynamic buttons Instead of horizontally.

while(id <rowcount+2)

{

tr = new TableRow(MainActivity.this);

table.addView(tr);

Button btn1 = new Button(MainActivity.this);

btn1.setText("");

btn1.setOnClickListener(this);

btn1.setId(id);

tr.addView(btn1);

id++;

}

网友答案:

you are creating new object of TableRow each time, TableRow represents elements in Horizontal and TableLayout represent data in Vertical that's why you getting Buttons in Vertical manner

tr = new TableRow(MainActivity.this);
while(id <rowcount+2)
{
Button btn1 = new Button(MainActivity.this);
btn1.setText("");
btn1.setOnClickListener(this);
btn1.setId(id);
tr.addView(btn1);   
id++;   
}
table.addView(tr);
网友答案:

you are creating a new row each time for the loop
try this.

    tr = new TableRow(MainActivity.this);

    while(id <rowcount+2) {
      Button btn1 = new Button(MainActivity.this);
      btn1.setText("");
      btn1.setOnClickListener(this);
      btn1.setId(id);
      tr.addView(btn1);   
      id++;   
    }
   table.addView(tr);
相关阅读:
Top