Aligning TextViews in a TableRow

Ryan R picture Ryan R · Jun 16, 2011 · Viewed 7.1k times · Source

I am trying to align 3 text views in a tablerow like this:

|------------------------------------------------|
| {TextView1} {TextView2}            {TextView3} |
|------------------------------------------------|

// TextView 1, 2 Left aligned
// TextView 3 Right aligned

Also, the table row should fill the table width.

With the code below I can only achieve this:

|------------------------------------------------|
| {TextView1} {TextView2} {TextView3}            |
|------------------------------------------------|

I code:

TableRow tr = new TableRow(myActivity.this);

TextView tvLeft = new TextView(myActivity.this);
tvLeft.setText(values[0]);

TextView tvCenter = new TextView(myActivity.this);
tvCenter.setText(values[1]);

TextView tvRight = new TextView(myActivity.this);
tvRight.setText(values[2]);
tvRight.setGravity(Gravity.RIGHT);

tr.addView(tvLeft);
tr.addView(tvCenter);
tr.addView(tvRight);

myTable.addView(tr);

The right text view is not gravitating to the right, AND the table row does not fill the table width. Do I need to use weights on the text views?

Edit: Added TableLayout:

<TableLayout 
android:layout_height="wrap_content"
android:id="@+id/myTable" 
android:layout_width="fill_parent" 
>
</TableLayout>

Answer

Glendon Trullinger picture Glendon Trullinger · Jun 16, 2011

Second Shot

I'm not sure whether you're creating the TableLayout programmatically or in XML or what the properties are, but it sounds like you want to

(in Java)

myTable.setColumnStretchable(2, true);

(in XML)

android:stretchColumns="2"