2013-12-07 46 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