Vertical Alignment gravity not responding

10,959

Solution 1

layout_gravity:
Standard gravity constant that a child can supply to its parent.

gravity:
Specifies how to place the content of an object, both on the x- and y-axis, within the object itself.

So if you want your content to be vertically centered you need gravity not layout_gravity.

Solution 2

Instead of using android:layout_gravity="center_vertical", please use android:gravity="center_vertical", It will work...:)

Share:
10,959
RileyE
Author by

RileyE

Updated on June 11, 2022

Comments

  • RileyE
    RileyE almost 2 years

    Why won't this center the contents in the view?

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_gravity="center_vertical"
        tools:context=".MainActivity">
    
        <EditText 
            android:id="@+id/messageTextField"
            android:layout_weight="1"
            android:inputType="number"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="@string/messageTextFieldPlaceholder"
        />
        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/sendButtonTitle"
            android:onClick="sendMessage"
        />
    
    </LinearLayout>
    

    I saw a few SO threads about vertical alignment and I have also seen this, but I only have a horizontal LinearLayout, so setting the gravity will adjust the views from side to side.

    Since the LinearLayout has the parent's dimensions, does it not fill the whole screen?

    Shouldn't android:layout_gravity="center_vertical" align it's subviews in the center (vertically) of it's dimensions?

    This is what makes sense to me across the coding that I've done, so why is android not making sense?

    Do I need another LinearLayout that is vertical that holds everything else inside of it and have that with android:layout_gravity="center_vertical"?

  • RileyE
    RileyE over 11 years
    Okay. So, layout_gravity is for the contents as it communicates to it's layout and gravity would be for the layouts as it adjusts it's contents, right?
  • Ahmad
    Ahmad over 11 years
    yes. layout_gravity -> child to parent, gravity -> parent to child.
  • RileyE
    RileyE over 11 years
    Thank you for the help. I had to go with Ahmad for the extra explanation, though.