我试图通过编程方式创建一个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的直接子项显示出来。我做错了什么?
tableRow
添加到tableLayout
中:tableLayout.addView(tableRow);
- Starwave