以编程方式添加到TableLayout的视图未显示

时间:2012-05-17 15:51:31

标签: android android-view android-tablelayout

我正在尝试向TableLayout添加视图,但它们根本不会显示(我正在模拟器上测试)。实际上我写了比这更多的代码,即将textviews添加到了tablerows中,但是我已经把它缩减到了这一点,即使这样也行不通。知道为什么吗?

以下是test.xml的代码:

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

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEST" >
    </TextView>
</TableRow>

</TableLayout>

和java代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.test);

    /* Find Tablelayout defined in test.xml */
    TableLayout tl = (TableLayout) findViewById(R.id.tableLayout);
    /* Create a new row to be added. */
    TableRow tr = new TableRow(this);
    tr.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
    /* 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));
}

当我在模拟器上测试时,我只看到带有硬编码字符串“TEST”的textview(在xml文件中定义)。

1 个答案:

答案 0 :(得分:11)

尝试不将buttonLayout设置为在向表格添加行时不添加TableLayout.LayoutParams

//b.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(b);
//tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
t1.addView(tr)

我认为TableLayout.LayoutParams导致了一些问题。

相关问题