Skip to main content

Android : Difference between gravity and layout_gravity

Points To Remember

There are two attributes for a View in android to align its content

  • gravity
  • layout_gravity

The basic difference between the two is that

  • android:gravity is used for child elements of the view.
  • android:gravity_layout is used for this element with respect to parent view.

So, if you have a layout like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="EkiRas"
android:textSize="22dp"
android:gravity="center"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
>
// Other Elements
</LinearLayout>
</LinearLayout>

In the above code,

  • outer LinearLayout will set its child elements in center.
  • TextView gravity:center will set its ocntent in center.
  • inner LinearLayout will be aligned in the center of its parent, that is outer LinearLayout.

Comments