Search code examples
androidandroid-layouttextviewandroid-xml

Android - Align different font-sizes on same baseline


I have 2 adjacent TextViews, each with a different string that has a different font size. I want the text to have the same baseline in each TextView. How can I do this?

Here is my layout:

   <LinearLayout
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:background="@color/colorAccentLight"
            android:textSize="18sp"
            style="@style/Base.TextAppearance.AppCompat.Medium"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="bottom"
            android:textAlignment="gravity"
            android:text="30"
        />
        <TextView
            android:background="@color/colorAccent"
            android:text="hello"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="bottom"
            android:textAlignment="gravity"
        />

    </LinearLayout>

Here is the current behavior, notice how the 2 TextViews have different baselines (the "hello" is lower than the 30) because the font for each TextView is a different size.

enter image description here


Solution

  • Change the height of both TextView elements to wrap_content. By default, a horizontal LinearLayout will automatically align the baseline of TextView children.

    If you're currently using match_parent for height in order to have a full-height background color, you'll have to think of a different way to accomplish that. You could, perhaps, use a background color on the LinearLayout and then only specify a background color on the larger TextView; this will give the same effect you have today.