How to center a two-line text in a TextView on Android?

shiami picture shiami · Jan 25, 2011 · Viewed 51.4k times · Source

I want to let it looks like this:

|    two    |
|   lines   |

Here is the current layout, not working at all.

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="two\nlines"
        android:layout_gravity="center_vertical"
        android:layout_centerInParent="true"/>
</RelativeLayout>

Any idea? Thanks!

Answer

Kevin Coppock picture Kevin Coppock · Jan 25, 2011

If you just want to center it (I'm assuming the \n is working to split the lines), just add android:gravity="center_horizontal" rather than layout_gravity.
Using layout gravity moves the actual TextView, using gravity affects the content of the TextView.