Tip 29: Use RelativeLayout whenever you can. AbsoluteLayout is deprecated, don’t use it. Often you will have a choice between RelativeLayout and LinearLayout, go with RelativeLayout as you’ll almost always end up with fewer layers in your view hierarchy. An example, suppose you want to make a view something like:
Box A takes up left half of the screen | Box B takes up right half of the screen
Your first instinct is probably to use:
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”
>
<TextView
android:text=”Box A takes up left half of the screen”
android:layout_width=”0dip”
android:layout_height=”wrap_content”
android:layout_weight=”1″
/>
<TextView
android:text=”Box B takes up left half of the screen”
android:layout_width=”0dip”
android:layout_height=”wrap_content”
android:layout_weight=”1″
/>
</LinearLayout>
That works just fine, but you could also use:
<RelativeLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”
>
<TextView
android:text=”Box A takes up left half of the screen”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_toLeftOf=”@+id/dummy_center”
/>
<View
android:id=”@+id/dummy_center”
android:layout_width=”0dip”
android:layout_height=”0dip”
android:layout_gravity=”center”
/>
<TextView
android:text=”Box B takes up left half of the screen”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_toRightOf=”@+id/dummy_center”
/>
</RelativeLayout>
This second form doesn’t look much better than the first, in fact it looks worse: we’ve introduced a whole new element. But suppose we want to add in image into each box, schematically:
Box A takes up left half IMAGE | Box B takes up right half IMAGE
Pursuing the first method, you’d need to introduce a second level of LinearLayouts, pursuing the second you could put your images directly into the same RelativeLayout – for example by specifying that the first image should be to the left of “dummy_center” and TextView A should be to the left of that. So you’d have 7 elements across 3 levels of view hierarchy (LinearLayout way), versus 6 elements across 2 levels (RelativeLayout). All this stuff adds up.