Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical Alignment gravity not responding

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"?

like image 315
RileyE Avatar asked Jan 04 '13 20:01

RileyE


2 Answers

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.

like image 110
Ahmad Avatar answered Nov 09 '22 01:11

Ahmad


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

like image 26
Vishesh Chandra Avatar answered Nov 09 '22 00:11

Vishesh Chandra