2011-08-30 58 views
0

我想在運行時將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); 
} 

任何指針將不勝感激。謝謝。

+0

粘貼您的logcat的。這可能是多種原因...例如,buttonList可能爲空(你是否實例化它?) – IncrediApp

+0

根據logcat,錯誤似乎發生在這一行CalculatorActivity.java:46這是 mainLayout。 addView(tblLayout); 我已經實例化buttonList。 –

回答

0

你的循環加載之前:

Arraylist<TableRow> tr = new ArrayList<TableRow>; 

在循環,而不是:

TableRow tr = new TableRow(this); 

地說:

tr.add(new TableRow(this)); 

最後取代你tr通過tr.get(r)。像這樣的改進的東西應該幫助你,因爲你在你的你的循環的每個回合擦除TR:

TableRow tr = new TableRow(this); 
0

開心快活人先生只是做一件事寫setContentView(R.layout.your Main Layout); beofre text = (EditText)findViewById(R.id.editText1); 指在onCreate()方法的頂部因爲我們不能前setContentView.

定義任何view沒有任何setContentView你不能找到像爲findViewById(R.id.editText1);

0

以下行會後的第一個任意視圖

setContentView(mainLayout); 

那麼只有findViewByid工作