2011-01-02

RelativeLayout alignment trick

Have you ever tried to place two buttons next to each other with each button taking up half the screen? Are you using RelativeLayout as well? Finding it hard? There is actually a pretty neat trick for this, using a View layout as a helper object. This will not be visible since the size is 0 pixels, and after centering the View horizontally, the buttons can be aligned to the left/right:
<View
 android:id="@+id/buttons_helper"
 android:layout_width="0dp"
 android:layout_height="0dp"
 android:layout_centerHorizontal="true" />
<ImageButton
 android:id="@+id/previous"
 android:src="@drawable/previous_btn"
 android:layout_toLeftOf="@id/buttons_helper"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:layout_alignParentBottom="true" />
<ImageButton
 android:id="@+id/next"
 android:src="@drawable/next_btn"
 android:layout_toRightOf="@id/buttons_helper"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:layout_alignParentBottom="true" />
Note that I'm using ImageButton above. You will have to reference a valid picture in android:src="@drawable/...", or simply use a Button object instead. This will result in the following layout:


This will be cheaper than having a LinearLayout with weight attributes set. If you know any other way to accomplish this with RelativeLayout, please let me know.

Inga kommentarer:

Skicka en kommentar