如何在LinearLayout单元格中对齐两个TextView?

4

我有一个垂直列表(垂直LinearLayout)。在每个单元格中,我有两个EditText字段,相邻放置。第一个应该对齐到单元格的左侧,第二个应该对齐到单元格的中间,基本上是两列并排。我认为我使用了双列GridLayout。然而令我惊讶的是,第二个EditText被对齐到单元格的右侧而不是单元格的中间。我做错了什么?

    <GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:alignmentMode="alignBounds"
    android:columnCount="2" >

    <TextView
        android:id="@+id/sourceLanguage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:text="test1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FF3366"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/targetLanguage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:gravity="left|center_vertical"
        android:text="test2"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#993366"
        android:textIsSelectable="true" />

</GridLayout>

输入图像描述 快到了,但还差一点……此外,第二列并没有完全左对齐。

这就是期望的结果!!!

输入图像描述

1个回答

17

使用 LinearLayoutweightSum。我修改了你的代码(见下文)。请注意在 LinearLayout 中添加的 weightSumTextView 的宽度变化以及 TextViewlayout_weights

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

    <TextView
        android:id="@+id/sourceLanguage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:text="test1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FF3366"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/targetLanguage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="left|center_vertical"
        android:text="test2"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#993366"
        android:textIsSelectable="true" />

</LinearLayout>

Shade,感谢您的回答。但是现在第二个TextView与单元格的50%对齐,而不是70%左右,请参见问题的屏幕截图。 - jhulst
@jhulst,是的,我的帖子被编辑了,我没有注意到重力已经改变了。我再次进行了编辑,现在应该没问题了。 - Shade
嘿哈!成功了(见屏幕截图问题),非常感谢! - jhulst

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