align text center with android

Tsunaze picture Tsunaze · Sep 6, 2011 · Viewed 326.6k times · Source

I know it sounds easy. I need to put a text in center, but when the text is too long it needs to go below, but still align in the center of my xml.

Here's my code :

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

I put paddingTop and Bottom because I need some space. PS: My code is bigger; it's in a RelativeLayout.

Answer

peter.bartos picture peter.bartos · Sep 6, 2011

Set also android:gravity parameter in TextView to center.

For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.