TextView FILL_PARENT不起作用

时间:2015-12-11 20:40:43

标签: android android-layout textview

我想让TextView填充父级,但我的代码不起作用。

这是我的代码:

TableLayout tableLayout = new TableLayout(this);

    TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
    TableRow.LayoutParams param = new TableRow.LayoutParams();

    tableRowParams.setMargins(1, 1, 1, 1);
    param.span = 2;
    param.setMargins(1, 1, 1, 1);

    int trainIndex = 0;
    int stationIndex = 1;


    for(int i = 0; i < 6; i++){
        TableRow row = new TableRow(this);

        if(i == 0){
            TextView text = new TextView(this);

            text.setText("Way");
            text.setBackgroundColor(Color.GRAY);
            text.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
            row.addView(text, tableRowParams);

            for(int j = 0; j < 4; j++) {
                TextView text1 = new TextView(this);

                text1.setText(getInfo(0, stationIndex));
                text1.setBackgroundColor(Color.GRAY);
                row.addView(text1, param);
                stationIndex++;
            }
        }else {

            for (int j = 0; j <= 8; j++) {
                TextView text = new TextView(this);


                if(j == 0){
                    text.setText(getInfo(1,trainIndex));
                    text.setBackgroundColor(Color.GRAY);
                    row.addView(text, tableRowParams);
                    trainIndex++;
                }else {
                    text.setText("   train  " + j);
                    text.setBackgroundColor(Color.GRAY);
                    row.addView(text, tableRowParams);
                }
            }
        }
        tableLayout.addView(row);
    }

    setContentView(tableLayout);

当我将布局参数应用于textview时,它不起作用,当文本不长时,它会在单元格中产生空白区域,我希望所有单元格都具有灰色背景。

以下是示例: enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您忘记为TextView设置LayoutParams。默认情况下,宽度和高度都使用WRAP_CONTENT。

另外,使用MATCH_PARENT而不是FILL_PARENT

修改

试试这个:

TableRow row = new TableRow(this);
TextView text = new TextView(this);
text.setText("Way");
text.setBackgroundColor(Color.GRAY);
text.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT));
row.addView(text);

答案 1 :(得分:0)

确保您的容器具有FILL_PARENT属性

TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT));