How to align LinearLayout at the center of its parent?

These two attributes are commonly confused:

  • android:gravity sets the gravity of the content of the View it's used on.
  • android:layout_gravity sets the gravity of the View or Layout relative to its parent.

So either put android:gravity="center" on the parent or android:layout_gravity="center" on the LinearLayout itself.

I have caught myself a number of times mixing them up and wondering why things weren't centering properly...


Please try this in your linear layout

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout 
            android:orientation="horizontal"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:text="1"
                 android:textAppearance="?android:attr/textAppearanceLarge" />

           <TextView
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:text="2"
                 android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>
</RelativeLayout>

consider wrapping relativeLayout over LinearLayout. android:layout_centerHorizontal="true" will position the view center horizontal.


add layout_gravity="center" or "center_horizontal" to the parent layout.

On a side note, your LinearLayout inside your TableRow seems un-necessary, as a TableRow is already an horizontal LinearLayout.