Thursday, October 18, 2012

Android RelativeLayout - A neat trick

Often when you are making a Layout in Android you want to have text and and icon that goes along with that text. Placing an icon on the left of the text is no problem. You just make the <ImageView/> view wrap_content in both width and height, while making the text that goes to the left of it fill_parent in width.

But if you want to have the icon on the right of the screen, and the text to the left of it spanning the whole width minus the width of the icon, it can get confusing. Thankfully we have <RelativeLayout>!

Here is an image of hat we want to achieve:

Here's how to achieve that:

<RelativeLayout        
     android:layout_width="fill_parent"
     android:layout_height="wrap_content">
   <ImageView             
             android:id="@+id/heart"
             android:src="@drawable/heart"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_alignParentRight="true" />
    <TextView
           android:layout_alignParentLeft="true"
           android:layout_toLeftOf="@id/heart"
           android:id="@+id/text" 
             android:layout_width="fill_parent" 
             android:layout_height="wrap_content"
           android:text="@string/text" />     
</RelativeLayout>

I marked the important bits in bold. Now for experienced developers this may seem obvious, but for someone new it might not be as clear. At least for me it was one of those "Aha!" moments. And that's why I decided to post it here.

No comments:

Post a Comment