2011-09-06 103 views
115

我知道這聽起來很容易。我需要將文本放在中間,但是當文本太長時,它需要放在下面,但仍然在我的xml中心對齊。將文本中心與android對齊

這裏是我的代碼:

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/showdescriptioncontenttitle" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp" 
    android:layout_centerHorizontal="true" 
> 
    <TextView 
     android:id="@+id/showdescriptiontitle" 
     android:text="Title" 
     android:textSize="35dp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    /> 
</LinearLayout> 

我把paddingTop和底部,因爲我需要一些空間。 PS:我的代碼更大;它在RelativeLayout中。

回答

311

還設置android:gravity參數TextViewcenter

爲了測試不同佈局參數的影響,我建議爲每個元素使用不同的背景顏色,以便您可以看到佈局如何隨着重力,layout_gravity或其他參數而改變。

+0

謝謝你,它的工作,只是需要一些時間來有效的回答! – Tsunaze

+1

我看到android:layout_centerHorizo​​ntal =「true」不再需要了.. – Tsunaze

+0

是的,那是真的。但我認爲只有當TextView有多行時才行。因爲只有1個不是全行的文本,TextView不會橫向填充佈局 –

4

您可以使用以下方法:

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/showdescriptioncontenttitle" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp"> 

<TextView 
     android:id="@+id/textview1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:text="Your text" 
     android:typeface="serif" /> 
</LinearLayout> 

佈局需要是相對的「中心」屬性被使用。

14

用這種方式在XML

<TextView 
     android:id="@+id/myText" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Time is precious, so love now." 
     android:gravity="center" 
     android:textSize="30dp" 
     android:textColor="#fff" 
     /> 
4

添加在你的TextView會做的伎倆android:gravity="center"(是父佈局Relative/Linear)!

此外,你應該避免使用字體大小的dp。改爲使用sp。

1

附加layout_gravity並用的重力中心值在TextView的

<TextView 
    android:text="welcome text" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_gravity="center" 
    android:gravity="center" 
    />