Aligning TextViews in a TableRow

假装没事ソ 提交于 2020-01-14 07:44:08

问题


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>

回答1:


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"



回答2:


I think Relative layout is better. Try this

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


来源:https://stackoverflow.com/questions/6367494/aligning-textviews-in-a-tablerow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!