AlanSTACK
AlanSTACK

Reputation: 6065

layout_gravity="center_vertical" not working

My problem

I can't seem to figure out why android:layout_gravity="center_vertical" is not working in my case.

Please note that I am not interested in solving the problem of making it vertically aligned, so much so that I am trying to understanding exactly what is the cause of this behavior itself for pedagogical reasons.

My code

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue_100">

    <android.support.v7.widget.AppCompatTextView
        android:background="@color/red_100"

        android:text="HELLO WORLD"
        android:textSize="18sp"
        android:textColor="@color/black"

        android:gravity="center_vertical"
        android:maxLines="2"

        android:layout_gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</android.support.v7.widget.LinearLayoutCompat>

enter image description here

Upvotes: 3

Views: 3123

Answers (2)

Anne L
Anne L

Reputation: 1

I'm not sure why it is but if you change your layout height to wrap content instead of match parent, it will be centered.

Upvotes: 0

Ben P.
Ben P.

Reputation: 54234

A LinearLayout with vertical orientation will ignore the vertical component of any child's android:layout_gravity attribute. Similarly, a LinearLayout with horizontal orientation will ignore the horizontal component of a child's android:layout_gravity.

For the special case of the center gravity value, it's helpful to know that this behaves identically to center_horizontal|center_vertical, down to the actual integer value of the constants (0x11 vs 0x01|0x10). As such, using android:layout_gravity="center" in a vertical linear layout will be equivalent to just android:layout_gravity="center_horizontal".

As for why, consider this:

<LinearLayout orientation=vertical>

    <View layout_gravity=top/>
    <View layout_gravity=bottom/>

</LinearLayout>

What would you do here? If you position the first view at the top of the screen and the second view at the bottom of the screen, then you're not really a linear layout.

Even though you said you're not interested in how to solve the problem, you can do so with the android:gravity attribute on the LinearLayout itself. This will cause the LinearLayout to stack all the views together at the top, center, or bottom of the linearlayout.

Upvotes: 5

Related Questions