android:gravity="top" doesn't align child view to top, but "center" aligns to center?

House3272 picture House3272 · Jun 4, 2013 · Viewed 9k times · Source
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="top"   <!--this line-->
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="56dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="36dp" />
</LinearLayout>

Shouldn't that make the smaller "0" t-view align to the top of the inner LinearLayout? Since the other "0" is larger in height, it increases the overall height of the inner LinearLayout.

Alternatively, if you included this:

android:layout_gravity="top"

within the t-view of the smaller 0, it also does nothing. Why is this? Does the wrap_content of the LinearLayout wrap each individual view independent of others? If so, then why does setting gravity to "center" work? In the sense that the smaller zero is vertically centered to its parent.

I know you can just set the smaller 0's height to match parent and set its own gravity to top. I'm just trying to understand this. Thanks.

Answer

Alex Wang picture Alex Wang · Feb 22, 2018

The default behavior of the layout is to align the baselines of the text, which in English are at the bottom of the view. Adding android:baselineAligned="false" to your LinearLayout will align the second TextView at the top of the view.