10

我正在尝试在一个表格中对齐 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 
android:layout_height="wrap_content"
android:id="@+id/myTable" 
android:layout_width="fill_parent" 
>
</TableLayout>
4

2 回答 2

9

第二枪

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

(在 Java 中)

myTable.setColumnStretchable(2, true);

(在 XML 中)

android:stretchColumns="2"
于 2011-06-16T05:35:25.960 回答
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);
于 2011-06-16T06:19:52.213 回答