扩展TableLayout类 - 添加行

时间:2011-01-24 15:17:54

标签: android android-widget android-layout

我正在尝试扩展TableLayout类,以便类将自动填充行。我遇到的问题是我在自定义类中添加的行不显示。

实施例。在活动中:

private TextView getTableCell(String text) {
    TextView tv = new TextView(this);
    tv.setText(text);
    tv.setLayoutParams(new LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));

    return tv;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DatasetTableLayout table = (DatasetTableLayout) findViewById(R.id.table);
    TableRow tr = new TableRow(this);
    tr.addView(getTableCell("activity1"));
    tr.addView(getTableCell("activity2"));
    tr.addView(getTableCell("activity3"));
    table.addView(tr);

这成功地向表中添加了一行。但是,在我的自定义类中:

private TextView getTableCell(String text) {
    TextView tv = new TextView(context);
    tv.setText(text);
    tv.setLayoutParams(new LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT));

    return tv;
}

private void update() {
    TableRow tr = new TableRow(context);
    tr.addView(getTableCell("class1"));
    tr.addView(getTableCell("class2"));
    tr.addView(getTableCell("class3"));
    addView(tr);
}

无法成功添加行。好吧,它确实添加了一行,如getChildCount()和getChildAt()确实返回此行 - 但它不会显示。

我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

我的猜测就是这一行:addView(tr);它是否成功将TableRow添加到TableLayout

编辑:

TableLayout tb = new TableLayout(this);
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
tv.setText("row");
tr.addView(tv);
tb.addView(tr); // this is what I mean
setContentView(tb);

您创建行的代码运行正常,但如果您尚未将其添加到表中,以后再将该表添加到父视图中,则不会显示您的行。

答案 1 :(得分:0)

@theresia(如果我添加评论,似乎无法格式化文本): 看起来它确实添加了TableRow:

for(int i = 0; i < getChildCount(); i++) {
    TableRow row = (TableRow) getChildAt(i);
    for(int j = 0; j < row.getChildCount(); j++) {
        TextView tv = (TextView) row.getChildAt(j);
        Log.e("DatasetTableLayout-data", tv.getText().toString() + " ");
    }
}

给了我:

01-24 11:03:31.668: ERROR/DatasetTableLayout-data(1624): activity1 
01-24 11:03:31.677: ERROR/DatasetTableLayout-data(1624): activity2 
01-24 11:03:31.698: ERROR/DatasetTableLayout-data(1624): activity3 
01-24 11:03:31.698: ERROR/DatasetTableLayout-data(1624): class1 
01-24 11:03:31.698: ERROR/DatasetTableLayout-data(1624): class2 
01-24 11:03:31.727: ERROR/DatasetTableLayout-data(1624): class3