相对布局中TextView水平居中

71

在我的应用程序屏幕上,我希望横向居中显示标题。 我尝试了以下布局xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip"
  >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Connections" />
</RelativeLayout>

谢谢


1
应用程序名称在Android中居中对齐 - NagarjunaReddy
1
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="10dip"
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Connections" /> </RelativeLayout>
- Android
6个回答

162

android:gravity 控制 TextView 内部文本的对齐方式。因此,如果您有两行文本,它们将在 TextView 的界限内居中对齐。尝试使用 android:layout_centerHorizontal="true"


1
请注意,如果RelativeLayout包含属性android:gravity="center_horizontal",则此方法将无法正常工作。 - CoolMind
6
如果这样不起作用,确保你的文本视图宽度也设置为 "wrap_content" 而不是 "match_parent"。 - Munib
将 TextView 的宽度设置为 "wrap content" 会导致其不可见。 - meekash55
android:layout_centerHorizontal="true" android:gravity="center"我认为这是正确的。这样TextView将在布局中居中,文本将在TextView中居中。 - Venus

20

使用这个:

android:layout_centerHorizontal="true"

在TextView内部


7
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip"
    >
  <TextView
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Connections" />
</RelativeLayout>

5

使用layout_centerInParent="true"(layout_centerInHorizontal,layout_centerInVertical)

Gravity指的是文本在TextView中的对齐方式,而不是视图本身


4

请使用以下代码替换文本视图

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:text="Connections" />

谢谢,它正在工作,我认为唯一的区别是将“wrap_content”改为“fill_parent”。 - Riskhan

3

只需添加此代码 android:gravity="center_horizontal"

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip" 
  android:gravity="center_horizontal"
  >
  <TextView

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Connections" />
</RelativeLayout>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接