TableLayout以编程方式

时间:2017-03-14 13:06:28

标签: java android xml

我们希望以编程方式实例化TableLayout,其中包含undefined个行和按钮。我们开发了以下代码,但是当我们打开应用程序时,它没有显示所有按钮(表格比屏幕大得多)。

private void setButtons() {
    TableLayout table = (TableLayout) view.findViewById(R.id.table);
    TableRow row;
    TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT);
    lp.bottomMargin = 32;
    lp.topMargin = 32;
    LevelButton button;

    for (int i = 0; i < Constants.ROW_NUM; i++) {
        row = new TableRow(table.getContext());
        row.setLayoutParams(lp);
        row.setGravity(Gravity.CENTER | Gravity.BOTTOM);

        for (int j = 0; j < Constants.BUTTON_NUM; j++) {
            button = new LevelButton(row.getContext());
            TableRow.LayoutParams lpb = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
            lpb.leftMargin = 32;
            lpb.rightMargin = 32;
            button.setLayoutParams(lpb);
            button.setLevelNumber((i*6)+j+1);
            if (j == 1) {
                button.setState(LevelState.ZERO_STARS);
            }
            row.addView(button);
            Log.println(Log.DEBUG, "debug", "" + row.getLayoutParams().height);
        }
        table.addView(row);
    }
}

Screen view

1 个答案:

答案 0 :(得分:0)

你的TableLayout似乎是正确的。但是你应该将你的布局添加到ScrollView:

看看: ScrollView with TableLayout programmatically Java