gpt4 book ai didi

android - 以编程方式创建 TableLayout

转载 作者:IT老高 更新时间:2023-10-28 22:14:03 25 4
gpt4 key购买 nike

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

最佳答案

只是为了让答案更清楚:

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时,你应该传递父 View 的LayoutParams

关于android - 以编程方式创建 TableLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com