Search code examples
androidcode-behindandroid-tablelayout

Creating table layout and adding rows from the code behind in Android


I need to create a table layout and add rows dynamically from Java code behind. I have already read questions here, but they are mentioning to add table rows in an already created table layout (from xml).

I need to create the table layout as well as add data to it dynamically. Can anyone please provide some inputs?

For now, I have linear layout code in place which adds button from code behind one below the other, I need to place it under a tabular format now.


Solution

  • To add three buttons to TableRow use the code below

    TableLayout tableLayout = new TableLayout(this);
        for (int i = 0; i < 10; i++)
        {
            TableRow tableRow = new TableRow(this);
            Button button = new Button(this);
            button.setText("1");
            tableRow.addView(button);
    
            button = new Button(this);
            button.setText("2");
            tableRow.addView(button);
    
            button = new Button(this);
            button.setText("3");
            tableRow.addView(button);
    
            tableLayout.addView(tableRow);
        }
        setContentView(tableLayout);