【问题标题】:Unable to center the text in TextView when width is set to 'match_parent'当宽度设置为“match_parent”时,无法将 TextView 中的文本居中
【发布时间】:2023-03-16 05:13:01
【问题描述】:

我对 Android SDK 比较陌生,并且在我的活动 UI 上使用 TextView 以及其他组件。当我将宽度设置为 wrap_content 并使用 layout_gravity 时,我可以将 TextView 置于父容器的中心。但是,我现在需要为 TextView 提供一个完全沿父级宽度延伸的背景,因此我将宽度设置为 match_parent。一旦我这样做了,layout_gravitytextAlignment="center" 都无法在视图中居中显示文本。这是我正在使用的代码:

<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: 而不是android:layout_gravity:

标签: android layout textview text-align


【解决方案1】:

使用gravity 而不是layout_gravity

它们之间的区别

android:gravity 设置其使用的视图内容的重力,android:layout_gravity 设置其父视图或布局的重力。

试试这个应该可以解决你的问题。

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="@string/trackName"
    android:textColor="#ffffff"
    android:gravity="center"
    android:textSize="28sp"
    android:paddingTop="7dp"
    android:paddingLeft="20dp"
    android:background="#99000000" />

【讨论】:

    【解决方案2】:
    android:gravity="center_horizontal"
    

    gravity 和 layout_gravity 的区别:

    layout_gravity 表示宽度在其布局中的重力。您已将宽度用作 match_parent。所以你的 textview 已经占据了所有的空间。

    gravity 表示该视图内容的重力。即文本视图中文本的重力。您必须将该文本放在中心,而不是 textview。

    【讨论】:

      【解决方案3】:

      您应该使用android:gravity。正如文档所说:

      gravity 指定对象应如何在其自身边界内定位其内容,在 X 和 Y 轴上。

      layout_gravity 子级提供给其父级的标准重力常数。定义子视图应如何在其封闭布局内的 X 轴和 Y 轴上定位。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-30
        • 1970-01-01
        • 2015-10-10
        相关资源
        最近更新 更多