Search code examples
androidtextviewalignmentvertical-alignment

Android: TextViews next to each other on different screen sides


I'm struggling with TextViews. I want them next to each other but in the opposite screen sides. First should be on the left of the screen and the second on the right. This is my code:

<LinearLayout android:layout_width="match_parent"
                              android:layout_height="wrap_content"
                              android:orientation="horizontal">
                    <TextView android:layout_width="match_parent"
                              android:layout_height="match_parent"
                              android:id="@+id/unit"
                              android:textSize="22sp"
                              android:text="Unit"/>
                    <TextView android:layout_width="match_parent"
                              android:layout_height="match_parent"
                              android:id="@+id/unitName"
                              android:text="Km"
                              android:textColor="@android:color/darker_gray"
                              android:textSize="22sp"/>
</LinearLayout>

I tried layout_gravity and gravity and it doesn't work. I was experimenting with wrap_content and match_parent but still my TextViews are just next to each other. I want them in opposite screen sides. What should I do?


Solution

  • Change your width to Wrap_content and Linear layout to RelativeLayout and then set alignParent attributes

    <RelativeLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/unit"
            android:layout_alignParentLeft="true"
            android:textSize="22sp"
            android:text="Unit"/>
    
        <TextView
            android:id="@+id/unitName"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="right"
            android:layout_alignParentRight="true"
            android:text="Km"
            android:textColor="@android:color/darker_gray"
            android:textSize="22sp" />
    </RelativeLayout>