Search code examples
javaandroidandroid-layoutandroid-5.0-lollipopandroid-relativelayout

Aligning two TextViews in Android


I have two TextViews aligned in the "row", using the following layout:

<RelativeLayout
        android:id="@+id/wrapper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp">
        <TextView
            android:id="@+id/big_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true" 
            android:textSize="21sp"/>

        <TextView
            android:id="@+id/small_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>

But, what happens is that since the left one is larger than the right one, the result looks like this (picture is just for illustration):

Bad behaviour

Instead, this is what I'm looking for:

enter image description here

Tried adding gravity="bottom" to the small TextView but it didn't work. Also tried to wrap the small TextView in another layout, set it's layout height to match_parent (so it would take the height of the big TextView) and then set the small TextView gravity to bottom, but it also didn't work.

Edit: plot twist: how to align it to the CENTER of the big TextView?


Solution

  • Add this line to your smaller textview

    android:layout_alignBaseline="@+id/big_text" 
    

    or

    android:layout_alignBottom="@+id/big_text"
    

    like this:

    <RelativeLayout
            android:id="@+id/wrapper"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp">
            <TextView
                android:id="@+id/big_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true" 
                android:textSize="21sp"/>
    
            <TextView
                android:id="@+id/small_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:layout_alignBaseline="@+id/big_text" 
                android:layout_alignParentRight="true"/>
        </RelativeLayout>