How to align two TextViews within LinearLayout cell?

jhulst picture jhulst · Mar 22, 2013 · Viewed 9.4k times · Source

I have a vertical list (vertical LinearLayout). Within Each cell I have two EditText fields, next to each other. The first should be aligned to the left of the cell, the second aligned to the middle of the cell, basically resulting in two columns next to each other. I thought I used a two column GridLayout. To my surprise however, the second EditText is aligned to the right of the cell rather than the middle of the cell. What do I wrong?

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

enter image description here Almost there, but not quit... besides the second column is not exactly left-aligned.

Here is the desired result!!!

enter image description here

Answer

Shade picture Shade · Mar 22, 2013

Use a LinearLayout and weightSum. I modified your code (see below). Note the added weightSum in the LinearLayout, the changed widths of the TextViews and the layout_weights of the TextViews:

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