Android:以编程方式在TableLayout中拉伸行

Jav*_*lar 4 android android-layout

我正在尝试动态创建一个TableLayout,它的所有行都被拉伸,就像本教程中所示.我已经通过XML完成了它,但我想从Activity中完成它.这是我迄今为止尝试过的代码没有成功:

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;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你提前.

编辑

Screenshot of what I have
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

what I expect
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Luk*_*rog 14

你的行需要父母的LayoutParams:

tableRow.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.FILL_PARENT, 1.0f));
Run Code Online (Sandbox Code Playgroud)

  • @Waqas你需要父母的'LayoutParams`.按钮有`TableRow`参数,行有`TableLayout`参数,表应该有`LinearLayout`参数(我认为它适用于`TableLayout`,因为`TableLayout.LayoutParams`来源于` LinearLayout.LayoutParams`,也是`TableLayout`是`LinearLayout`的扩展. (4认同)
  • 我还有一个问题:为什么当像我这样的可怜的家伙将错误的LayoutParams推送到视图时,地狱机器人甚至不会发出任何警告或异常? (2认同)