从代码中定位TableActivity上的按钮

时间:2013-11-02 07:09:27

标签: java android button

我用按钮创建表3x3。

for (int i = 0, lenI = field.length; i < lenI; i++) {
        TableRow row = new TableRow(this);
        row.setWeightSum(1);
        for (int j = 0, lenJ = field[i].length; j < lenJ; j++) {
            Button button = new Button(this);
            buttons[i][j] = button;
            button.setOnClickListener(new Listener(i, j));
            row.addView(button, new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.MATCH_PARENT));
            button.layout(Gravity.CENTER, Gravity.CENTER, Gravity.CENTER, Gravity.CENTER);
        }
        layout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.MATCH_PARENT));
    }

如何将它们放在屏幕中央并设置屏幕宽度的1/3?现在按钮位于活动的左侧。

1 个答案:

答案 0 :(得分:0)

添加按钮时,请使用以下代码。最后一个参数'1'代表重量。

row.addView(button, new TableRow.LayoutParams(0,
                    TableRow.LayoutParams.MATCH_PARENT, 1));

修改:See docs