使TableLayout列以编程方式完全适合其内容的大小

时间:2013-01-11 22:24:14

标签: android android-tablelayout

我正在尝试在Android中创建一个表(最低API级别为10),其中一些列必须尽可能地拉伸,而有些列需要缩小以适应其内容的大小。

这就是我所拥有的:

(颜色只是看细胞的宽度和高度)

'at'栏就是我所说的。我需要它看起来像这样:

http://img268.imageshack.us/img268/1572/77141b8b8eb443d783cede5.png

以下是我现在使用的代码:

ScrollView sv = new ScrollView(this);

    TableLayout table = new TableLayout(this);
    table.setShrinkAllColumns(true);
    table.setStretchAllColumns(true);
    table.setPadding(10, 10, 10, 10);

    //title row
    TableRow rowTitle = new TableRow(this); 
    rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);  
    TextView title = new TextView(this);  
    title.setText("Majors - Season 10");  
    title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);  
    title.setGravity(Gravity.CENTER);
    title.setTypeface(Typeface.SERIF, Typeface.BOLD);  
    TableRow.LayoutParams params = new TableRow.LayoutParams();  
    params.span = 4;
    rowTitle.addView(title, params);

    //header row
    TableRow rowHeaders = new TableRow(this);

    TextView away = new TextView(this);  
    away.setText("Away");
    away.setTypeface(Typeface.DEFAULT_BOLD);
    away.setGravity(Gravity.CENTER_HORIZONTAL);
    rowHeaders.addView(away);

    TextView empty = new TextView(this);
    empty.setText("  ");
 //     empty.setGravity(Gravity.CENTER_HORIZONTAL);
    empty.setBackgroundColor(Color.GREEN);
    rowHeaders.addView(empty);

    TextView home = new TextView(this);  
    home.setText("Home");  
    home.setTypeface(Typeface.DEFAULT_BOLD);  
    home.setGravity(Gravity.CENTER_HORIZONTAL);
    rowHeaders.addView(home);

    TextView score = new TextView(this);  
    score.setText("Score");  
    score.setTypeface(Typeface.DEFAULT_BOLD);
    score.setGravity(Gravity.RIGHT);
    rowHeaders.addView(score);

    TableRow rowMatch = createMatchRow();  
    TableRow rowMatch2 = createMatchRow();

    table.addView(rowTitle);  
    table.addView(rowHeaders);  
    table.addView(rowMatch);  
    table.addView(rowMatch2);  

    sv.addView(table);
    return sv;

createMatchRow()只是一个为每个匹配返回TableRow的方法。 (第2行 - )

1 个答案:

答案 0 :(得分:5)

呃,通过删除

来修复它
table.setShrinkAllColumns(true);
table.setStretchAllColumns(true);

并添加:

table.setColumnStretchable(0, true);
table.setColumnStretchable(2, true);