以编程方式在TableRow中正确设置TextView重力 [英] Programmatically set TextView gravity right in a TableRow
问题描述
我知道这个问题已经被问了好几次了,但是在我的情况下似乎无法使其正常工作.我正在尝试使最后一列在以编程方式生成的表中对齐.我知道我需要将LayoutParams应用于行和所有内部子项,并且我需要将Gravity设置为TextView,而不是行,但是我已经尝试了所有我能想到和不能想到的排列似乎使最后一列右对齐.
I know this has been asked several times over, but can't seem to get it to work correctly in my situation. I am trying to get the last column to align right in a table that is generated programatically. I know I need to apply the LayoutParams to the row and all the inner children, and I know that I need to set the Gravity to the TextView, not the row, but I have tried all the permutations I can think of and can't seem to get the last column to align right.
这是我的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>
然后在我的活动中,我循环执行以下代码
And then in my activity I have the following code in a loop
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
的宽度字段:
In order for setGravity()
to work you must first modify the width field of yourTextView
as follows in your layout:
android:layout_width="fill_parent"
现在您应该可以拨打电话了:
Now you should be able to call:
tvPeriodHours.setGravity(Gravity.RIGHT)
这篇关于以编程方式在TableRow中正确设置TextView重力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!