我知道这已经被问了好几次了,但似乎无法让我的情况正常工作。我正在尝试使最后一列在以编程方式生成的表中正确对齐。我知道我需要将 LayoutParams 应用于行和所有内部子项,并且我知道我需要将重力设置为 TextView,而不是行,但我已经尝试了我能想到的所有排列,似乎无法让最后一列正确对齐。
这是我的 XML 布局:
<!--Open Hours-->
<LinearLayout
android:id="@+id/llOpenHourDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/llWebsiteDetail"
android:paddingBottom="10dp"
android:visibility="gone"
android:weightSum="4">
<TextView
android:id="@+id/tvOpenHourDetailIcon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/fa_clock"
android:textColor="@color/cp_blue" />
<TableLayout
android:id="@+id/tlOpenHoursDetail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3" />
</LinearLayout>
然后在我的活动中,我循环了以下代码
String currentPeriod = formattedOpen.format(open.getTime()) + " - " +
formattedClose.format(close.getTime());
TableRow.LayoutParams params = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT );
TableRow tableRow = new TableRow(getBaseContext());
tableRow.setLayoutParams(params);
TextView tvDayOfWeek = new TextView(getBaseContext());
tvDayOfWeek.setText(open.getDisplayName(
Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()));
tvDayOfWeek.setTextColor(getResources().getColor(R.color.black));
tvDayOfWeek.setLayoutParams(params);
tableRow.addView(tvDayOfWeek);
TextView tvPeriodHours = new TextView(getBaseContext());
tvPeriodHours.setText(currentPeriod);
tvPeriodHours.setTextColor(getResources().getColor(R.color.black));
tvPeriodHours.setGravity(Gravity.RIGHT);
tvPeriodHours.setLayoutParams(params);
tableRow.addView(tvPeriodHours);
tlOpenHoursDetail.addView(tableRow);
为了使setGravity()
正常工作,您必须首先在布局中修改TextView
的宽度字段,如下所示:
android:layout_width="fill_parent"
现在您应该能够调用:
tvPeriodHours.setGravity(Gravity.RIGHT)
我认为有两种方法可以做到这一点。
-
如果 TableLayout 的宽度不是基于其内容(例如,如果列宽是使用
android:stretchColumns
设置的),则可以将 TextView 宽度设置为match_parent
,然后使用textView.setGravity(Gravity.END)
在 TextView 上分配重力。 -
如果 TextView 宽度小于 TableLayout 单元格的边界,则可以使用
tableRow.setGravity(Gravity.END)
调用 TableRow 上的重力。
我有一个表格布局,其中我的文本视图填充单元格的宽度而不是高度,所以我使用:
textView.setGravity(Gravity.CENTER);
tableRow.setGravity(Gravity.CENTER_VERTICAL);
将我的文本放在单元格的正中心。
万一它对任何人有帮助,我花了很长时间试图让 TextView 与单元格底部对齐,但似乎没有任何效果,包括tableRow.setGravity(Gravity.CENTER_VERTICAL)
,不知道为什么,但我已经放弃了,在中心很好。