在TableRow中对齐TextView

时间:2011-06-16 05:27:42

标签: android textview alignment tablerow

我试图在这样的一个tablerow中对齐3个文本视图:

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

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

此外,表格行应填充表格宽度。

使用下面的代码,我只能做到这一点:

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

我代码:

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);

右侧文本视图不会向右移动,并且表格行不会填充表格宽度。我是否需要在文本视图中使用权重?

编辑:添加了TableLayout:

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

2 个答案:

答案 0 :(得分:8)

第二次拍摄

我不确定您是以编程方式还是以XML格式创建TableLayout,或者属性是什么,但听起来您想要

(在Java中)

myTable.setColumnStretchable(2, true);

(以XML格式)

android:stretchColumns="2"

答案 1 :(得分:1)

我认为相对布局更好。试试这个

    RelativeLayout tr = new RelativeLayout(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]);

    tr.addView(tvLeft); 

    RelativeLayout.LayoutParams relativeLayoutParamsCenter = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    relativeLayoutParamsCenter.addRule(RelativeLayout.RIGHT_OF, tvLeft.getId());
    tr.addView(tvCenter,relativeLayoutParamsCenter);

    RelativeLayout.LayoutParams relativeLayoutParamsRight = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);        
    relativeLayoutParamsRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);      
    tr.addView(tvRight,relativeLayoutParamsRight);

    myTable.addView(tr);