17

Possible Duplicate:
Android - gravity and layout_gravity

I have been working on android xml's. I have used android:layout_gravity="center" to align components in specific position.

Now a days, when I was working on a Dialog like Activity, I came across android:gravity="center". What I found there was, gravity was used to align its child to a specific position.

I would share an example of what it is,

android:gravity="center"

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical" >
            <EditText
                android:id="@+id/enterNumberEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:hint="Enter No." >

                <requestFocus />
            </EditText>
            </LinearLayout>

It aligns the child of LinearLayout in center.

android:layout_gravity="center"

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:background="@drawable/dialog_background" >
</LinearLayout>

It aligns the LinearLayout itself in center.

Now my questions are:

  1. If I am right in these assumptions, that whether gravity is for child components and layout_gravity is for parent component.
  2. When to choose gravity over layout_gravity.

I have found this much explanation working on xml's so far. I would like to hear much better explanation of it. Let me know, if I am wrong somewhere

Community
  • 1
  • 1
Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
  • 2
    `gravity` aligns the content of a view, `layout_gravity` aligns a view within its parent. – K-ballo Dec 20 '12 at 05:30
  • These videos helped me a lot to understand the difference: https://www.youtube.com/watch?v=DxfYeAUd238 – Shomu Oct 13 '18 at 12:29

3 Answers3

11
  1. Yes, your understanding is correct. Any layout_ attribute gives instructions to the parent view.
  2. Generally, if a view is taking up the full width/height of its' parent, then you won't need to specify layout_gravity, you'll probably find gravity more useful. If your view does not take up an entire dimension of its' parent, you might want to align it depending on your desired look.
wsanville
  • 37,158
  • 8
  • 76
  • 101
4

Their name should help you :
android:gravity sets the gravity of the content of the View its used on.
android:layout_gravity sets the gravity of the View or Layout in its parent.

For more info visit this site

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
1

android:gravity sets the gravity of the content of the View its used on.

android:layout_gravity sets the gravity of the View or Layout in its parent.

Rajeev N B
  • 1,365
  • 2
  • 12
  • 24