Search code examples
androidgravitylayout-gravity

The difference between vertical and horizontal orientation about layout_gravity and gravity


I have a TextView in a LinearLayout.

I want to try different modes for layout_gravity and gravity.

I have this code:

<LinearLayout
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:background="#A55C93"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/textView1"
        android:background="#005Cff"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="50dp"
        android:layout_height="25dp"
        android:text="text"
        android:textSize="21sp" />
</LinearLayout>

When I have android:orientation="vertical", everything about layout_gravity and gravity makes sense. But when I have android:orientation="horizontal", outputs are different from the first, why?


Solution

  • The main thing to understand is that layout_gravity on a child view is an attribute that communicates "up" to the parent, and "asks" the parent to behave in a certain way.

    In this case, the parent is a LinearLayout, which has a different attribute (orientation) that already affects the positioning of child views. Therefore, when a child specifies layout_gravity, what happens depends on the LinearLayout's orientation.

    • For a horizontal LinearLayout, any horizontal component of the child's layout_gravity is ignored.
    • For a vertical LinearLayout, any vertical component of the child's layout_gravity is ignored.

    You're using center, which is basically center_vertical + center_horizontal. So for a horizontal LinearLayout, the horizontal centering will be ignored. And, for a vertical LinearLayout, the vertical centering will be ignored.

    Given that your example only has one child view, you could consider replacing the parent LinearLayout with a FrameLayout. Then the child layout_gravity will be fully respected.