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);
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);
2 Responses to “Creating a tableLayout dynamically in Android”
Jaimin Patel
Using above code will i be able to create multiple rows and columns ??
And also i need to provide id to table layout to bind it in activity ??
Mashruf
yes you shall be able to create multiple rows and columns. if you use view binding or use libraries like butterknife(which is deprecated now) then you don’t have to provide id.