-1

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++;   

}
android_eng
  • 1,370
  • 3
  • 17
  • 40

2 Answers2

0

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);
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
0

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);
Rohit Patil
  • 1,068
  • 8
  • 9