以编程方式创建TableLayout [英] Create TableLayout programmatically
本文介绍了以编程方式创建TableLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以编程方式创建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?
推荐答案
只是使答案更清楚:
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
Explanation
When you call setLayoutParams
, you are supposed to pass the LayoutParams
of the parent view
这篇关于以编程方式创建TableLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文