以编程方式创建TableLayout

时间:2009-10-07 01:02:50

标签: android tablelayout

我正在尝试以编程方式创建TableLayout。它不会起作用。然而,xml文件中的相同布局有效。这就是我所拥有的:

public class MyTable extends TableLayout
{
    public MyTable(Context context) {
        super(context);

        setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        TableRow row = new TableRow(context);
        row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        Button b = new Button(getContext());
        b.setText("hello");
        b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
        row.addView(b); 
        addView(row)
    }
}

...

// In main activity:
MyTable table = new MyTable(this);
mainLayout.addView(table);

当我跑步时,我没有崩溃,但没有出现。如果我摆脱TableRow实例,至少该按钮确实显示为TableLayout的直接子项。我做错了什么?

5 个答案:

答案 0 :(得分:33)

只是为了让答案更清楚:

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

TableLayout tableLayout = new TableLayout(context);
tableLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// assuming the parent view is a LinearLayout

TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(tableParams);// TableLayout is the parent view

TextView textView = new TextView(context);
textView.setLayoutParams(rowParams);// TableRow is the parent view

tableRow.addView(textView);

<强>解释
当您致电setLayoutParams时,您应该传递父视图的LayoutParams

答案 1 :(得分:6)

事实证明我需要为布局参数指定TableRowLayout,TableLayout等,否则表格不会显示!

答案 2 :(得分:1)

一个好的解决方案是为要创建的每个行实例充气布局文件。请参阅此帖子:How to duplicate Views to populate lists and tables?

答案 3 :(得分:0)

对我来说,为了得到我,我不得不打电话给addContentView()

答案 4 :(得分:0)

你的问题就在这一行:

b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

您需要将LayoutParams更改为TableRow.LayoutParams

b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));