使用Java代码对TableLayout行进行居中

时间:2013-01-07 20:52:03

标签: android tablelayout

我想创建一个TableLayout并将其内容集中。 我写了这段代码:

TableLayout tl = new TableLayout(this);
tl.setGravity(Gravity.CENTER);

TableRow firstRow = new TableRow(this);
TableRow secondRow = new TableRow(this);

但它不起作用。行是居中但只是垂直......我该怎么办?

提前致谢。

编辑:

TableLayout tl = new TableLayout(this);
tl.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));

TableRow firstRow = new TableRow(this);
TableRow secondRow = new TableRow(this);

firstRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, Gravity.CENTER));
secondRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, Gravity.CENTER));

1 个答案:

答案 0 :(得分:0)

您应该为TableLayout设置LayoutParams并在其上设置重力:

tl.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL) );