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:

           android:layout_alignParentRight="true" />
           android:text="@string/text" />     

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