2012-02-03 84 views
46

在我的應用程序屏幕中,我想將標題顯示爲水平中心。我試圖與下面佈局XML代碼RelativeLayout中的TextView水平中心

<?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

請參閱http://stackoverflow.com/questions/8767655/application-name-center-alignment-in-android/8767692#8767692 – NagarjunaReddy 2012-02-03 05:33:42

+1

<?xml version =「1.0」encoding =「utf-8」?> <的RelativeLayout的xmlns:機器人= 「http://schemas.android.com/apk/res/android」 機器人:layout_width = 「FILL_PARENT」 機器人:layout_height = 「FILL_PARENT」 機器人:layout_marginTop = 「10dip」 > Android 2012-02-03 05:47:07

回答

114

android:gravity控制的TextView內的外觀。所以如果你有兩行文本,它們將會在TextView的邊界內居中。試試android:layout_centerHorizontal="true"

+2

謝謝你的好解決方案 – Riskhan 2012-02-03 05:41:34

+0

最受歡迎,祝你好運。 – 2012-02-03 05:42:18

+0

請注意,如果RelativeLayout包含屬性android:gravity =「center_horizo​​ntal」,則這將不起作用。 – CoolMind 2016-01-16 13:18:14

4

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

重力裝置的文字上的TextView褐藻膠,而不是視圖本身

+0

非常感謝你畝ch – Riskhan 2012-02-03 05:42:13

15

使用此:

android:layout_centerHorizontal="true" 

內的TextView

+0

非常感謝你 – Riskhan 2012-02-03 05:40:55

+0

小心在最後不必要的分號 – Matt 2015-01-06 16:56:58

+0

@Matt,我編輯了答案並刪除了不必要的分號。 ;) – ViliusK 2015-01-17 13:54:49

1

只添加這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> 
5
<?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> 
+0

嗨,感謝你的解決方案也工作 – Riskhan 2012-02-03 05:54:26

4

替換爲下面的代碼的TextView

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

謝謝你它工作,我認爲唯一的區別是wrap_content fill_parent – Riskhan 2012-02-03 06:01:41