thedarkpassenger
thedarkpassenger

Reputation: 7358

android:gravity="center" not working as expected

I have the following xml file

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#000000"
              android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:orientation="vertical"
        android:background="#ff0000">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00ff00"
            android:text="Button"
            android:layout_gravity="center"/>
    </LinearLayout>

</LinearLayout>

which has the following Design.

enter image description here

Shouldn't the button be placed in the center vertically as well? I know how the layout_gravity and gravity works. So according to my understanding the button should be definitely at the center both horizontally as well as vertically.

Upvotes: 5

Views: 8768

Answers (2)

thedarkpassenger
thedarkpassenger

Reputation: 7358

Based on @vspallas answer, I found the solution to my question. Basically the reason for this behavior is that I am specifying vertical orientation to my LinearLayout. It means that whatever views I place inside the layout should be shown in a vertical orientation i.e. one below the other. If I had three views inside my LinearLayout, then the result should be something like this

View1
View2
View3.

But if I did android:layout_gravity="center" for View2 and had it worked according to my expectation, then it would have placed View2 in the center, and not between View1 and View3 which will contradict the orientation attribute. Hence Android allows to set gravity to the parent itself which will make sure that all the views inherit the same gravity and are in the same orientation for LinearLayout.

Upvotes: 1

Vasileios Pallas
Vasileios Pallas

Reputation: 4867

You must add android:gravity="center" in your LinearLayout

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="100dp"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#ff0000">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="Button"
        android:layout_gravity="center"/>
</LinearLayout>

Upvotes: 10

Related Questions