如何在tablelayout中动态创建列?

时间:2012-03-01 06:31:12

标签: android android-tablelayout

我正在尝试了解如何动态地将列和行添加到tablelayout。

我有这个简单的例子。但是,它只显示运行时的第一列。

有人能告诉我缺少什么才能显示四列而不是一列吗?

package com.apollo.testtablelayout;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TestTableLayoutActivity extends Activity {
    /** Called when the activity is first created. */

    String col1;
    String col2;
    String col3;
    String col4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);

        for (int x = 1; x < 10; x++) {

            col1 = "(" + x + ") Column 1";
            col2 = "(" + x + ") Column 2";
            col3 = "(" + x + ") Column 3";
            col4 = "(" + x + ") Column 4";

            TableRow newRow = new TableRow(this);

            TextView column1 = new TextView(this);
            TextView column2 = new TextView(this);
            TextView column3 = new TextView(this);
            TextView column4 = new TextView(this);

            column1.setText(col1);

            newRow.addView(column1);
            newRow.addView(column2);
            newRow.addView(column3);
            newRow.addView(column4);

            tl.addView(newRow, new TableLayout.LayoutParams());
        }
    }

}

2 个答案:

答案 0 :(得分:4)

您需要为每个列文本

设置setText
column1.setText(col1); 
column2.setText(col2); 
column3.setText(col3); 
column4.setText(col4); 

答案 1 :(得分:0)

不要忘记每一列都需要新的TableLayout.LayoutParams(),这是我尝试向表格布局添加更复杂的视图时犯的错误。

newRow.addView(view, new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                            TableRow.LayoutParams.WRAP_CONTENT) );