2010-07-08 60 views
2

我最近開始使用Android玩arround。我試圖實現的第一件事之一是創建一個動態的TableLayout。在網上搜索時,我發現了一些示例代碼http://en.androidwiki.com/wiki/Dynamically_adding_rows_to_TableLayout,我將其複製到了我的活動中。動態添加行不可見

所以我的活動,現在看起來是這樣的:

public class FooActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.foo); 

     /* Find Tablelayout defined in main.xml */ 
     TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout); 

     for(int i= 0; i < 9; i++){ 

      /* Create a new row to be added. */ 
      TableRow tr = new TableRow(this); 
      tr.setLayoutParams(new TableRow.LayoutParams(
          LayoutParams.FILL_PARENT, 
          LayoutParams.WRAP_CONTENT)); 
      tr.setBackgroundColor(Color.MAGENTA); 

       /* Create a Button to be the row-content. */ 
       Button b = new Button(this); 
       b.setText("Dynamic Button"); 
       b.setLayoutParams(new LayoutParams(
          LayoutParams.FILL_PARENT, 
          LayoutParams.WRAP_CONTENT)); 

       /* Add Button to row. */ 
       tr.addView(b); 

     /* Add row to TableLayout. */ 
     tl.addView(tr,new TableLayout.LayoutParams(
       LayoutParams.FILL_PARENT, 
       LayoutParams.WRAP_CONTENT)); 
    } 
    } 

} 

我在佈局文件夾foo.xml看起來是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/myTableLayout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
<TableRow 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 

     <Button android:text="Static Button"/> 
</TableRow> 
</TableLayout> 

當我現在開始我的應用程序在模擬器中,沒有動態添加的行是可見的。我只看到了在foo.xml文件中定義的靜態按鈕。使用附加的調試器,我能夠看到我的代碼被執行,並且行被添加到tablelayout對象。但是,添加的行不會呈現。

任何想法?

回答