我试图以编程方式创建一个TableLayout。这是行不通的。在一个XML文件相同的布局工作,但。这是我有:
I'm trying to create a TableLayout programatically. It just won't work. The same layout in an xml file works though. This is what I have:
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的直接孩子。我究竟做错了什么?
When I run this, I don't get a crash, but nothing appears. If I get rid of the TableRow instance, at least the button does appear as a direct child of the TableLayout. What am I doing wrong?
感谢
只是为了让答案更加清晰:
Just to make the answer more clear:
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(tableParams);
TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(tableParams);
TextView textView = new TextView(context);
textView.setLayoutParams(rowParams);
tableRow.addView(textView);