Search code examples
androidandroid-relativelayout

Android RelativeLayout children to left and right


I am trying to create a layout where there is a RelativeLayout and two child inside it. The two children are TextView and ImageView. I want the text to start from the very left of the RelativeLayout and ImageView to very right of the RelativeLayout.

What properties I need to use?

The code is which is not working.

<RelativeLayout 
    android:clickable="true"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:background="@drawable/android_btn_large" 
    android:gravity="center_vertical">

    <TextView 
            android:id="@+id/txtButton"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:text="Riverside Park" 
            android:textColor="#FFFFFF"
            android:layout_alignParentLeft="true">
    </TextView>
    <ImageView 
            android:id="@+id/imgButton"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:src="@drawable/plus_icon_480">
     </ImageView>
</RelativeLayout>

The above works but stretch the button to fill_parent.


Solution

  • that should do the job

    <RelativeLayout 
        android:clickable="true"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:background="@drawable/android_btn_large"
        android:gravity="center_vertical">
    
    <TextView 
        android:id="@+id/txtButton"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/imgButton"
        android:text="Riverside Park"
        android:textColor="#FFFFFF"
        android:layout_alignParentLeft="true"></TextView>
    
    <ImageView 
        android:id="@id/imgButton"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/txtButton"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/plus_icon_480">        
    </ImageView>
    </RelativeLayout>
    

    notice that in TextView there is +id, and in ImageView there is no "+"". However you should use linear layout with weight set to "1" on both views.