ivanfeli
ivanfeli

Reputation: 230

Make TableLayout columns to fit perfectly the size of its contents programmatically

I'm trying to make a table in Android (API Level 10 minimum) where some of the columns have to stretch as more as possible whereas some need to shrink to fit its contents' size.

This is what I have:

(the colors are just to see the cells' width and height)

the 'at' column is what I am talking about. I need it to look like this one:

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

Here is the code I am using for now:

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() is just a method that returns a TableRow for each of the matches. (Rows 2-)

Upvotes: 2

Views: 7614

Answers (1)

ivanfeli
ivanfeli

Reputation: 230

Eh, fixed it by removing the

table.setShrinkAllColumns(true);
table.setStretchAllColumns(true);

and adding:

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

Upvotes: 6

Related Questions