Wednesday, March 7, 2012

Relative-ly Easy

Layout XML files are a huge part of Android. Layouts in general really, because anything you design in XML you can create in raw JAVA code as well, but let's face it, XML layouts make everyone's lives easier. According to Romain Guy the best layouts are flat (not a lot of nested widgets). What I see most often coming from new android devs (and I've done it before too) is something similar to this:
<LinearLayout android:orientation="vertical">
    <LinearLayout android:orientation="horizontal">
         <TextView android:text="@string/someLabel">
            <LinearLayout android:orientation="vertical">
                <TextView android:text="@string/someText"/>
                <TextView android:text="@string/someSubText"/>

Now obviously this code is not complete (lacking ids, layout_width/height, etc) but you get the idea. Three levels of depth when you could just have one if you use a RelativeLayout instead of nested LinearLayouts. There are a plethora of Layout Parameters to help you position your widgets. Here is an example of how you can achieve the same layout as above with just a single layer of depth using RelativeLayout:

<RelativeLayout xmlns:android=""
          <TextView android:id="@+id/myLabel"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true" /> <!-- this is really not required since the first                                                                                       
                                                                         view goes in the top left anyway -->
          <TextView android:id="@+id/myTitle"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_alignBaseline="@id/myLabel" />
          <TextView android:id="+id/mySubTitle"
                    android:layout_width="wrap_content" android:layout_height="wrap_content"
                    android:layout_below="@id/myTitle" />
And That's it! That will produce the same type of layout as if you used the nested LinearLayouts in the pseudo-code above. Not only is the depth of the layout smaller, but we used less widgets overall! If you can do this with layout containing a lot more views or widgets, you can greatly increase your performance. Just think of it as the time you're saving if findViewById() doesn't have to traverse so many Linear Layouts!

These links might prove to be helpful:

No comments:

Post a Comment