我是 Android SDK 的新手,在我的 Activity UI 上使用 TextView 以及其他组件。当我将宽度设置为 wrap_content
并使用 layout_gravity
时,我可以将 TextView 置于父容器的中心。但是,我现在需要为 TextView 提供一个沿父级宽度完全拉伸(stretch)的背景,因此我将宽度设置为 match_parent
。执行此操作后,layout_gravity
和 textAlignment="center"
都无法使文本在 View 中居中。这是我正在使用的代码:
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/trackName"
android:textColor="#ffffff"
android:layout_gravity="center"
android:textSize="28sp"
android:paddingTop="7dp"
android:paddingLeft="20dp"
android:background="#99000000" />
这是 Activity UI 现在的样子:
如何解决此问题并将我的文本与 TextView 控件的中心对齐?请帮忙!
最佳答案
你应该使用android:gravity
。正如文档所说:
gravity Specifies how an object should position its content, on both the X and Y axes, within its own bounds.
layout_gravity Standard gravity constant that a child supplies to its parent. Defines how the child view should be positioned, on both the X and Y axes, within its enclosing layout.
关于android - 当宽度设置为 'match_parent' 时,无法将 TextView 中的文本居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958941/