以编程方式创建TableLayout

28

我试图通过编程方式创建一个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个回答

42

为了让答案更加清晰明了:

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


4
应该是tableRow.setLayoutParams(rowParams)吧? - Leon
救星奖授予@Gigori A.和Mark。Gigori A.因为他的回答而获得此奖项,而Mark则因为他自己的回答而获得此奖项。 - Muneeb Mirza
很棒且有用的解决方案。顺便提一下,在将TextView添加到行之前,应先将行添加到表中。tableLayout.addView(tableRow); - The_Martian
3
我花了一个小时试图弄清楚我的错误所在——结果发现在你的代码中,你忘记将tableRow添加到tableLayout中:tableLayout.addView(tableRow); - Starwave
@The_Martian。实际上,这不是强制性的。首先填充行,然后将后者添加到表中也可以起作用。在我看来,这更直观。 - albaspazio

6
原来我需要为布局参数指定TableRowLayout、TableLayout等,否则表格就无法显示!

2
你能发布你的代码解决方案吗?看起来你已经在上面做了。 - Atma
4
谢谢!@Atma TableRows 应该使用 TableLayout.LayoutParams,而 TableRows 中的视图应该使用 TableRow.LayoutParams。 :) - Brayden
很糟糕,你需要明确地这样做,但它对我有用,谢谢! - Geert Weening
谢谢@Brayden!那是我在TableLayout子类中错过的小细节,它自动具有所有TableLayout.LayoutParams而不是TableRow.LayoutParams! - Anonsage

1

1

对我来说,要获取我的内容,我必须调用addContentView()


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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接