android-studiobuttontextviewandroid-linearlayout

Unwanted top margin on TextView with horizontal linear layout


Can Somebody explain why there is a margin above the textview with this layout? This seems like a bug to me. I can not find a way to remove this so that the TextView and Button start at the same height

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

    <TextView
        android:id="@+id/TV_TimeSpan"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="From: 15.05.2023 00:00\nTo: 17.05.2023 23:59\n\n" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change"
        android:onClick="B_ChangeTimestamp_onClick" />

</LinearLayout>

enter image description here

Here a dirty fix on the TextView Element:

android:layout_marginTop="-14dp"
android:layout_marginBottom="14dp"

Edit: The margin offset changes when a button has two lines of text to 10dp


Solution

  • Add android:baselineAligned="false" to the opening tag. LinearLayout's default behavior in horizontal mode aligns Views by their baselines. For TextView and Button (which is just a specialized TextView), that's defined as the baseline of the first line of text.

    Here is the answer from Mike.