我定義了我自己的tableLayout,它擴展了TableLayout。 在我的課堂我試圖創建MyTableLayout對象:如何通過findViewById設置'this'對象(TableLayout)?
int tableLayoutId = R.id.tableLayoutId;
MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayout(tableLayoutId);
在上面的最後一行,tableLayout調用函數「createTableLayout」的對象。在這個函數中,我試圖通過findviewById來設置它('this'對象),但我正在做一些愚蠢的事情。那麼我應該如何設置它?
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();
}
}
012:======================
閱讀板球評論後,我在我的課改變了代碼
我的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);
你不能指定'this' ...'new MyTableLayout(this);'從Activity中已經創建了你的類。它不需要ID。或者,您應該可以將TableLayout類添加到Activity xml佈局。 –