Android - 对齐不同字体大小的文字到同一基线

5

我有两个相邻的 TextView,每个都有不同字体大小的不同字符串。我希望每个 TextView 的文本具有相同的基线。我该如何实现?

这是我的布局:

   <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>

以下是当前行为,注意两个 TextView 的基线不同("hello" 比 30 低),因为每个 TextView 的字体大小不同。

enter image description here


2
还不能写评论。 你看了这里吗:(https://dev59.com/FF8d5IYBdhLWcg3wch2i)? - frumle
谢谢。我最终使用了这个解决方案(将两个TextView都包装在RelativeLayout中,并使用“align_baseline”属性)。 - Foobar
2个回答

11

ConstraintLayout 中,您可以简单地使用

app:layout_constraintBaseline_toBaselineOf="@+id/textView1"

2
将两个TextView元素的高度改为wrap_content。 默认情况下,水平LinearLayout将自动对齐TextView子项的基线。
如果您当前使用match_parent来设置高度,以获得全高度的背景颜色,则必须考虑其他实现方式。也许可以在LinearLayout上使用背景颜色,然后只在较大的TextView上指定背景颜色; 这将给您今天的相同效果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接