Understanding the difference between gravity and layout_gravity Android 22.05.2017

Understanding the difference between gravity and layout_gravity

Gravity is essentially alignment. For example, if you want to align a label’s text to the right, you would set its gravity to right. There are quite a few possible values for gravity, including left, center, right, top, bottom, center_vertical, clip_horizontal, and others.

Note that Android defines two similar gravity attributes: android:gravity and android:layout_gravity. Here’s the difference: android:gravity is a setting used by the View, whereas android:layout_gravity is used by the container (ViewGroup).

For example, you can set android:gravity to center to have the text in the EditText centered within the control. Similarly, you can align an EditText to the far right of a LinearLayout (the container) by setting android:layout_gravity="right".

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText 
        android:layout_width="wrap_content"
        android:gravity="center"
        android:layout_height="wrap_content" 
        android:text="Hello world!"
        android:layout_gravity="right"/>
</LinearLayout>
android_gravity_right.png

The difference between gravity and layout_gravity is subtle, but will be easy to understand after you try them out. gravity controls what happens inside a widget: you would use it, for example, to left-justify or center text within the widget. layout_gravity deals with the relationship between the widget and its parent. For instance, if our TextView had its width set to wrap_content , we could specify layout_gravity="center_horizontal" to center it horizontally within its parent LinearLayout.

So in general android:layout_gravity attribute is used by child views to tell their parent how they want to be placed inside it, while android:gravity is used by the parent layout to tell the child views how they should be placed inside it.

If you’ve worked with web pages, you can consider gravity to be like padding in CSS, whereas layout_gravity is like margins.