androidandroid-layoutandroid-gravity

Different Gravity of two textviews in a horizontal Linear Layout


I am using the following code and when I set gravity to the first textview to center, automatically the second textview's text is also getting aligned with the first one. Even Though I set the gravity of second view to top

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="96dp"
        android:text="New Text"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:text="New Text"
        android:id="@+id/textView2" />
</LinearLayout>

There was a solution in another question which says to wrap the 2nd textview in another LinearLayout. But why is it so?


Solution

  • A horizontal LinearLayout aligns its child Views by their baselines by default, so the second TextView is being moved to align its text with the first's. To fix your problem, simply set the LinearLayout's baselineAligned attribute to false.

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false">