TableLayoutを拡張する独自のtableLayoutを定義しました。 私のクラスでは、私はMyTableLayoutオブジェクトを作成しようとしています:上記の最後の行でfindViewByIdで 'this'オブジェクト(TableLayout)を設定する方法は?
int tableLayoutId = R.id.tableLayoutId;
MyTableLayout tableLayout = new MyTableLayout(this);
tableLayout.createTableLayout(tableLayoutId);
、関数「createTableLayout」を呼び出すtableLayoutオブジェクトを。この関数では、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);
...
}
}
または多分私は他の方法でそれを行う必要がありますか?
====================================
== ============= EDIT ================
============== ======================
クリケットのコメントを読んだ後、私は私のクラスのコードを変更:
if (getResources() != null) {
MyTableLayout tableLayout = (MyTableLayout)
getResources().getLayout(R.layout.tableLayout);
if (tableLayout != null) {
tableLayout.createTableLayout();
}
}
my 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); 'を割り当てることはできません。 IDは必要ありません。代わりに、TableLayoutクラスをActivity xmlレイアウトに追加することができます。 –