Android - Center Textview in LinearLayout

user222786 picture user222786 · Jul 10, 2013 · Viewed 44.1k times · Source

I am trying to center a TextView in a LinearLayout and it is centering horizontaly but not vertically.

below is my code

 <LinearLayout
        android:orientation="vertical"
        android:layout_width="320dp"
        android:layout_height="50dp"
        android:background="@drawable/rectblack"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:minWidth="25px"
        android:minHeight="25px">
        <TextView
            android:text="Explode a Vin"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tvExVin" />
    </LinearLayout>

In the end I would like it to be centered vertically to the left of the Linearlayout, if someone could figure out how to do that, that would be great.

Thanks!

Answer

invertigo picture invertigo · Jul 10, 2013

You have the gravity and layout_gravity reversed. You can have multiple values on the gravity attribute separated by "|". Try this:

 <LinearLayout
        android:orientation="vertical"
        android:layout_width="320dp"
        android:layout_height="50dp"
        android:background="@drawable/rectblack"
        android:layout_marginTop="10dp"
        android:layout_gravity="center_horizontal"
        android:gravity="center_vertical|left"
        android:minWidth="25px"
        android:minHeight="25px">
        <TextView
            android:text="Explode a Vin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvExVin" />
    </LinearLayout>

For clarification:

android:layout_gravity="center_horizontal" will center the LinearLayout horizontally in its parent.

android:gravity="center_vertical|left" will center the TextView (and any other children) vertically inside the LinearLayout and align it to the left.