LinearLayout put child at the right side

My way (using a RelativeLayout):

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/productPriceTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Rs 3579.0"
    />
    <Button
        android:id="@+id/buyNowButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Buy Now"
    />
</RelativeLayout>

See how I explicitly align the TextView to the Parent's left side and the Button to the Parent's right side

You can then center the TextView vertically in the RelativeLayout, by setting:

android:layout_centerVertical="true"

in the TextView itself


Newr OS versions may prefer this:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/productPriceTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:text="Rs 3579.0"
    />
    <Button
        android:id="@+id/buyNowButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="Buy Now"
    />
</RelativeLayout>

Try below xml:

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/productPriceTextView1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:text="Rs 3579.0"
        />

    <Button
        android:id="@+id/buyNowButton1"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="Buy Now" />
</LinearLayout>

There is a cleaner way to do this, using LinearLayout : just give the left element a width of 0 and a weight of 1, and set the right one's width on wrap_content. And that's it!

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

    <TextView
        android:id="@+id/productPriceTextView1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Rs 3579.0" 
        />

    <Button
        android:id="@+id/buyNowButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Buy Now" />
</LinearLayout>