Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create columns in a tablelayout?

I'm trying to get an understanding of how to dynamically add columns and rows to a tablelayout.

I have this simple example. However, it only shows the first column when ran.

Can someone tell me what is missing in order to display four columns instead of one?

package com.apollo.testtablelayout;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TestTableLayoutActivity extends Activity {
    /** Called when the activity is first created. */

    String col1;
    String col2;
    String col3;
    String col4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);

        for (int x = 1; x < 10; x++) {

            col1 = "(" + x + ") Column 1";
            col2 = "(" + x + ") Column 2";
            col3 = "(" + x + ") Column 3";
            col4 = "(" + x + ") Column 4";

            TableRow newRow = new TableRow(this);

            TextView column1 = new TextView(this);
            TextView column2 = new TextView(this);
            TextView column3 = new TextView(this);
            TextView column4 = new TextView(this);

            column1.setText(col1);

            newRow.addView(column1);
            newRow.addView(column2);
            newRow.addView(column3);
            newRow.addView(column4);

            tl.addView(newRow, new TableLayout.LayoutParams());
        }
    }

}
like image 977
L. D. James Avatar asked Mar 01 '12 06:03

L. D. James


People also ask

How to add table row dynamically in android?

This example demonstrates how to add table rows Dynamically in Android Layout. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

You need to have the setText for each of the columns text

column1.setText(col1); 
column2.setText(col2); 
column3.setText(col3); 
column4.setText(col4); 
like image 129
Roberto Avatar answered Sep 21 '22 14:09

Roberto