问题
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