2013-05-12 142 views
2

我一直在做這個作業,但是我遇到的所有建議似乎都沒有工作。我是新來的Android應用程序,雖然答案可能是簡單一些,我不能看到我錯了....在TextView字段中換行後的文本居中

我有一個包含了換行符的字符串值,一個TextView場(\ n )。在圖形輸出中,文本的下行不居中TextView容器。我的代碼如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <TextView 
     android:id="@+id/textView4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/textView5" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="15dp" 
     android:text="@string/maxText" 
     android:textAlignment="gravity" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:textStyle="bold" /> 

</RelativeLayout> 

我的字符串如下:

<string name="maxText">My text part 1:\nMy text part 2</string> 

輸出的文本的低線左對齊的容器,但我需要它的中心。我已經嘗試了我在論壇中遇到的所有建議 - 但無濟於事。

任何幫助將不勝感激。

回答

0

解決這個問題的唯一明智的方法是創建兩個文本的意見,與第二個正下方的第一,並設置爲android:layout_gravity="center"android:gravity="center"

+0

謝謝,Neoh。有點認爲。只是認爲它會很好地添加一小段代碼而不是另一個TextView容器...... – Titch2K6 2013-05-12 10:03:53

0

你可以在你的類試試這個代碼,我用它來按鈕,它運作良好,兩條線都居中。我想它應該工作相同的TextView

String styledText = "My text part 1" + "<br />" + "My text part 2";   
textView.setText(Html.fromHtml(styledText)); 

注:所以你將不得不separatly聲明2串並從資源

+0

您是否嘗試過我的建議? – 2013-05-21 00:29:02

+1

沒有爲我工作。即使與

標籤也試過。什麼對我來說是設置text.setGravity(Gravity.CENTER);每次通過代碼更新TextView時。 – 2013-09-11 09:29:05

1

讓他們其實我們並不需要把文本分成兩個文本視圖。

爲包含XML文件中textview的佈局設置android:layout_gravity="center"

如果這不起作用。

嘗試設置佈局參數的重心,並以編程方式將此參數設置爲佈局。如下所示。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
params.gravity = Gravity.CENTER; 
yourLayout.setLayoutParams(params); 
yourLayout.setGravity(Gravity.CENTER); 

這對我有效。

希望這對你也能正常工作。 :)