android - 当宽度设置为 'match_parent' 时,无法将 TextView 中的文本居中

标签 android layout textview text-align

我是 Android SDK 的新手,在我的 Activity UI 上使用 TextView 以及其他组件。当我将宽度设置为 wrap_content 并使用 layout_gravity 时,我可以将 TextView 置于父容器的中心。但是,我现在需要为 TextView 提供一个沿父级宽度完全拉伸(stretch)的背景,因此我将宽度设置为 match_parent。执行此操作后,layout_gravitytextAlignment="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 现在的样子:

enter image description here

如何解决此问题并将我的文本与 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/

相关文章:

android - ellipsize ="marquee"在微调器中不起作用

android - 如何在Android中将图标垂直对齐到第一行textview的中心

android - 图标大小android,最常见的填充/大小facebook/youtube

android - 当用户单击文本和图标时更改颜色的命令是什么

java - 如何使用 dagger 限定符注释来提供不同的 OkHttpClient 构建器?

java - 如何仅将属性设置为 android 的搜索栏缩略图?

android - 如何解决在 Android 上使用空文本自动调整 TextView 的提示字符换行?

android - 如何在 Fragment 之间传递值

Android:使用 edittext 输入设置按钮的文本?

android - ImageView 太小