Android TextView不会水平居中

Android TextView不会水平居中,android,layout,Android,Layout,我的布局如下: <TextView android:id="@+id/display_city" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/pollenType" android:layout_alignParentBottom="true" android:layout_alignPa

我的布局如下:

<TextView
    android:id="@+id/display_city"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/pollenType"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/get_pollen_index"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_marginTop="51dp"
    android:textSize="40sp" />

可以看出,
宾夕法尼亚州费城
是左对齐的。无论我改变什么,不管它是水平居中还是垂直居中,它都保持左对齐

我尝试过通过XML和图形用户界面更改布局。在图形用户界面中,它确实是“居中的”,但它仍然是非居中的。我的布局位置在我所有的文本视图中都是一致的,所以我不确定为什么这个特定的文本视图没有居中


您正在告诉
显示城市
文本视图与屏幕一样宽

android:layout_width="match_parent"
但是,其文本默认为左对齐。这就是为什么它看起来像这样

对于您想要的东西,您有两种选择:

  • 将宽度保持为
    match_parent
    ,并将文本居中放置在文本视图中(使用
    重力
  • 将宽度设置为
    wrap\u content
    ,并将视图居中放置在其父视图内(使用
    layout\u gravity

  • 可以使用重力xml属性将文本居中:

    android:gravity="center"
    

    您的宽度等于
    match\u parent
    ,因此
    TextView
    的边缘已经接触到父视图的边缘。您应该在
    文本视图中使用
    android:gravity=“center”
    两个选项将文本居中放置

    One:给出文本视图
    android:layout\u width=“wrap\u content”

    Two:保留
    android:layout\u width=“match\u parent”
    并使用
    android:gravity=“center\u horizontal”

    layout\u gravity
    定义视图在其父视图中的重力。由于
    match\u parent
    ,您的文本视图已经占据了整个宽度,因此将其水平居中于其父视图内不会产生任何效果


    另一方面,
    gravity
    定义了内容的重力。

    使用
    android:gravity=“center”
    Ah修复它。。我应该为所有其他文本视图使用重心吗?奇怪的是,这是唯一一个不对齐的TextView。发布所有xmllayout@theGreenCabbage:文本视图使用属性(centerInParent、centerHorizontal或centerVertical)在屏幕上居中显示。但是,为了使文本视图中的文本居中,应该经常使用重力属性。