Creating a tableLayout dynamically in Android

Leave a comment

Creating layouts using xml is easy. But creating layouts in runtime is the only option sometimes…

TableLayout tableLayout = (TableLayout) findViewById(R.id.layoutTable);

        LinearLayout.LayoutParams tableRowParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        /* create a table row */
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(tableRowParams);

        /* create cell element - textview */
        TextView tv = new TextView(this);
        tv.setBackgroundColor(0xff12dd12);
        tv.setText("dynamic textview");

        /* create cell element - button */
        Button btn = new Button(this);
        btn.setText("dynamic btn");
        btn.setBackgroundColor(0xff12dd12);

        /* set params for cell elements */
        TableRow.LayoutParams cellParams = new TableRow.LayoutParams(0, TableRow.LayoutParams.MATCH_PARENT);
        cellParams.weight = 3;
        tv.setLayoutParams(cellParams);
        cellParams.weight = 2;
        cellParams.rightMargin = 10;
        btn.setLayoutParams(cellParams);

        /* add views to the row */
        tableRow.addView(tv);
        tableRow.addView(btn);

        /* add the row to the table */
        tableLayout.addView(tableRow);

Leave a Reply