如何以编程方式居中TableRow

时间:2015-08-09 14:28:46

标签: android android-layout android-tablelayout

我正在以编程方式在表格行中创建多个按钮,但它们总是以左对齐方式结束。我怎样才能将整行排成一行?我正在尝试创建每一行:

TableRow row = new TableRow(getActivity());
TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
row.setLayoutParams(params);

for (int j = 0; j != numButtonCols; j++) {
    Button b = new Button(getActivity());
    b.setOnClickListener(actionListener);
    row.addView(b);
    actionButtons[j][i] = b;
}

layout.addView(row);

2 个答案:

答案 0 :(得分:7)

您只需使用Gravity将行居中。只需使用

将其设置为您的行
isInterrupted()

答案 1 :(得分:0)

试试这个:

    TableRow row = new TableRow(getActivity());
    TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
    row.setLayoutParams(params);

    TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);

    for (int j = 0; j != numButtonCols; j++) {
        Button b = new Button(getActivity());
        b.setLayoutParams(buttonParams);
        b.setOnClickListener(actionListener);
        row.addView(b);
        actionButtons[j][i] = b;
    }

layout.addView(row);