2013-12-07 40 views
0

我在xml中有一個TableLayout,我想以編程方式向它添加行。視圖動態添加到TableLayout不顯示

這是我的代碼:

LinearLayout deckBuilder = (LinearLayout) getLayoutInflater().inflate(R.layout.deckbuilder, null); 

TableLayout deckGrid = new TableLayout(this.getApplicationContext()); 

    int rows = getResources().getInteger(R.integer.deckbuilder_grid_rows); 
    int columns = getResources().getInteger(R.integer.deckbuilder_grid_columns); 

    deckGrid.setWeightSum(rows); 

    for (int i = 0; i < rows; ++i) { 
     TableRow row = new TableRow(this.getApplicationContext()); 
     for (int j = 0; j < columns; ++j) { 
      ImageView iv = new ImageView(this.getApplicationContext()); 
      row.addView(iv); 
      iv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); 
      iv.setImageResource(R.drawable.my_image); 
     } 
     deckGrid.addView(row); 
     row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, 1)); 
    } 
    deckBuilder.addView(deckGrid); 
    deckGrid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 

的問題是,我在加入行的觀點都沒有顯示出來,該行本身沒有顯示向上。

行:3列:5

下面是deckbuilder的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/deckbuilder_background" 
    android:orientation="vertical" > 
</LinearLayout> 
+0

嗨,首先,您不應該使用applicationCOntext創建UI組件,其次您是否打印出行​​和列的值,如果是的話,請讓我們知道這些數字,而且我們可以更容易地幫助您如果你想在這裏添加deckbuilder的xml – Cata

回答

0

我想你的代碼是擴展Activity一個類裏面。

所以你應該把

setContentView(deckBuilder); 

最後一行之後顯示LinearLayout

此外,在Activity內,您可以直接使用this代替this.getApplicationContext()

+0

setContentView(deckBuilder)在類的開始處完成。 我試圖使用'this'而不是this.getApplicationContext(),但它仍然沒有工作 –

+0

嘗試發佈更多的代碼。在我的設備中,它工作... – xonya