I'm trying to create a TableLayout dynamically which has all its rows stretched like shown in this tutorial. I've accomplished it via XML, but I'd like to do it from the Activity. Here is the code I've tried so far without success:
public View getTableWithAllRowsStretchedView() {
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT));
tableLayout.setWeightSum(4);
for (int i = 0; i < 4; i++) {
TableRow tableRow = new TableRow(this);
tableRow.setGravity(Gravity.CENTER);
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));
for (int j = 0; j < 4; j++) {
Button button = new Button(this);
final int buttonNumber = (j + i * 4);
button.setText("" + buttonNumber);
button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT));
tableRow.addView(button);
}
tableLayout.addView(tableRow);
}
linearLayout.addView(tableLayout);
return linearLayout;
}
Thank you very much in advance.
EDIT
Screenshot of what I have
what I expect
Your rows need the parent's LayoutParams
:
tableRow.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.FILL_PARENT, 1.0f));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With