在Android中对齐两个文本视图的基线

22
请查看我的布局及其结果;我需要文本“Text message”与文本“Header”的基线对齐(请查看以下代码和快照)。如果有人能给我指导,我将不胜感激。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1.0"
android:baselineAligned="true"
>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.2"
    android:background="@color/custom_orange"
    android:gravity="center"
    >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Header"
        android:textSize="25sp"
        android:id="@+id/title"
        android:gravity="center"
        android:background="@color/custom_red"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Text message"
        android:textSize="10sp"
        android:id="@+id/language"
        android:gravity="center"
        android:background="@color/custom_green"/> 
</LinearLayout>

</LinearLayout>

这是结果

enter image description here

这是我需要的

enter image description here

4个回答

37

使用RelativeLayout作为TextView的容器,并添加属性

android:layout_alignBaseline="@+id/title"

id/language TextView


6

对于 ConstraintLayout,只需使用以下内容↓即可将其与另一个 textView 的基线对齐:

app:layout_constraintBaseline_toBaselineOf="@+id/textView"

4
只需在LinearLayout(两个TextView所在的线性布局)上使用android:gravity="bottom",并在两个TextView中都使用android:layout_height="wrap_content"即可。

实际上它确实可以。当我意外发现这一点时,我感到非常惊讶。现在我正在努力理解它的原理。 - Sviatoslav Melnychenko
7
我知道这已经很旧了,但我还是想把它留在这里,因为我认为这很有帮助,LinearLayouts有一个属性叫做“baselineAligned”(默认打开),它正如其名所示:根据它们的基线对齐视图(几乎每个TextView子类),除非它们有一个重心,这就是为什么OP的布局没有正确工作的原因。更多信息请参见:https://possiblemobile.com/2013/10/shifty-baseline-alignment/ - Jonathan Hernández
@JonathanHernández 感谢您留下评论和链接,确实非常有帮助! - Giulio Piancastelli

1
在组件树中选择你想要在同一个基线上的两个组件,右键单击,然后选择显示基线。只需拖动这两个组件的基线即可。

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