我定义了自己的tableLayout,扩展了TableLayout。 在我的课堂上,我尝试创建MyTableLayout对象:
int tableLayoutId = R.id.tableLayoutId;
MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayout(tableLayoutId);
在上面的最后一行中,对象tableLayout调用函数' createTableLayout'。在这个函数中,我试图通过findviewById设置它('这个'对象),但我猜想我做了些傻事。那我应该怎么设置呢?
public class MyTableLayout extends TableLayout {
public MyTableLayout(Context context) {
super(context);
}
public void createTableLayout(int tableLayoutId) {
// what should I write here(instead the line below) in order to let
// 'this' have the returned view from findViewById
this = (MyTableLayout) findViewById(tableLayoutId);
...
}
}
或者我可能会采取其他方式吗?
====================================
===============编辑================
====================================
在阅读了板球评论后,我改变了班级中的代码:
if (getResources() != null) {
MyTableLayout tableLayout = (MyTableLayout)
getResources().getLayout(R.layout.tableLayout);
if (tableLayout != null) {
tableLayout.createTableLayout();
}
}
我的xml包含MyTableLayout对象,我想通过它以编程方式创建表。
我的MyTableLayout看起来如此:
public class MyTableLayout extends TableLayout {
public MyTableLayout(Context context) {
super(context);
}
public void createTableLayout() {
for (int i = 0; i < numRows; ++i) {
TableRow tableRow = new TableRow(getContext());
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
for (int j = 0; j < numCols; ++j) {
MyButton myButton = new MyButton(getContext(), buttonId, buttonViewHeight, buttonViewWidth, buttonViewText);
myButton.setLayoutParams(new TableRow.LayoutParams(buttonViewHeight, buttonViewWidth));
tableRow.addView(myButton);
}
addView(tableRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
}
}
现在我的应用程序崩溃了。你知道为什么吗?
断点到达此行并崩溃:
MyTableLayout tableLayout = (MyTableLayout)
getResources().getLayout(R.layout.tableLayout);
答案 0 :(得分:0)
终于成功了。
<强> 1 强>
我从xml中删除了MyTableLayout。
<强> 2 强>
在班级&#39; onCreate我访问了我要添加MyTableLayout的布局:
linearLayoutGame = (LinearLayout) findViewById(R.id.linearLayout);
第3 强>
我创建并将其添加到此布局
MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayout();
linearLayout.addView(tableLayout);