如何在 Android (RelativeLayout) 中水平居中?

How do I horizontally center this in Android (RelativeLayout)?

我有以下代码:

<TextView
    android:id="@+id/exercise_name_label"
    android:layout_width="match_parent"
    android:layout_height="32dp"
    android:text="Curls"
    android:gravity="bottom"
    android:layout_centerHorizontal="true"
    />

而且我希望文本在 32dp 的底部对齐并水平居中..目前它不是水平居中的:

选项 1: 您应该将重力调整为 center_horizontal|bottom =)

<TextView
    android:id="@+id/exercise_name_label"
    android:layout_width="match_parent"
    android:layout_height="32dp"
    android:text="Curls"
    android:gravity="center_horizontal|bottom" />

选项 2: 您应该将宽度调整为 wrap_content 和 center_horizontally in parent =)

<TextView
    android:id="@+id/exercise_name_label"
    android:layout_width="wrap_content"
    android:layout_height="32dp"
    android:text="Curls"
    android:gravity="bottom"
    android:layout_centerHorizontal="true" />

android:layout_centerInParent="true"就是你想要的。但我必须说你不应该使用相对布局。我认为线性布局更稳定。

如果您想将其更改为线性布局,您可以使用 android:layout_gravity="center"

将这些属性设置为您的 TextView:

<!-- It will make your layout center horizontal relative to parent -->
android:layout_centerHorizontal="true"

<!-- It will draw your text from center of the area assigned to textview-->
android:gravity="center"