我想在運行時將tableLayout添加到main.xml中的現有LinearLayout。 我在main.xml中添加了editText(R.id.editText1)。這是我的代碼。它不工作。我得到一個運行時錯誤(應用程序意外停止)。Android - 在運行時向主佈局添加布局
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
text = (EditText)findViewById(R.id.editText1);
TableLayout tblLayout = new TableLayout(this);
tblLayout.setLayoutParams(new TableLayout.LayoutParams(8,5));
tblLayout.setPadding(1,1,1,1);
for(int r=0; r<ROW_COUNT; ++r)
{
TableRow tr = new TableRow(this);
for(int c=0; c<COL_COUNT; ++c)
{
int index = r * COL_COUNT + c;
buttonList.add(new Button(this));
buttonList.get(index).setText(buttonNames[index]);
tr.addView(buttonList.get(index), 60, 30);
}
tblLayout.addView(tr);
}
LinearLayout mainLayout = (LinearLayout)findViewById(R.layout.main);
mainLayout.addView(tblLayout);
setContentView(mainLayout);
}
任何指針將不勝感激。謝謝。
粘貼您的logcat的。這可能是多種原因...例如,buttonList可能爲空(你是否實例化它?) – IncrediApp
根據logcat,錯誤似乎發生在這一行CalculatorActivity.java:46這是 mainLayout。 addView(tblLayout); 我已經實例化buttonList。 –