27

我正在尝试以编程方式创建 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 的直接子级。我究竟做错了什么?

4

5 回答 5

39

只是为了让答案更清楚:

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父视图的

于 2012-12-21T10:52:41.877 回答
6

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

于 2009-10-07T01:28:33.120 回答
1

一个好的解决方案是为您要创建的每个行实例扩展布局文件。请参阅这篇文章:如何复制视图以填充列表和表格?

于 2014-01-11T06:39:13.757 回答
0

对我来说,要得到我的,我必须打电话addContentView()

于 2012-04-14T04:51:08.307 回答
0

您的问题出在这一行:

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

您需要更改LayoutParamsTableRow.LayoutParams

b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
于 2016-11-09T06:46:55.957 回答