以编程方式添加的TableRow不显示

时间:2011-12-30 18:56:47

标签: android layout

在我的xml布局中,我有

    <TableLayout
         android:id="@+id/gridview"
         android:layout_height="fill_parent"
         android:layout_width="fill_parent" >
    </TableLayout>

和活动

    setContentView(R.layout.main);


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

但是,tablelayout中的按钮和textview不会显示。知道为什么吗?

2 个答案:

答案 0 :(得分:3)

请务必使用LayoutParams的{​​{1}},否则TableLayoutLayoutParams无效,如下所示:

TableRow

或只是导入TableRow tr = new TableRow(this); tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT));

TableLayout.LayoutParams

答案 1 :(得分:0)

尝试删除此内容:

TableRow tr = new TableRow(this);
    tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));