Android: 2 relative layout divided in half screen

iGio90 picture iGio90 · Nov 14, 2013 · Viewed 71.7k times · Source

I tried many times to draw 2 Relative layout aligned horizontally and divided in half screen.

enter image description here

I design the image with paint to explain a bit better what i mean.

Any suggestion?

Answer

KevBry picture KevBry · Mar 12, 2014

Another way to accomplish the same task without needing to use a LinearLayout is to put a center-aligned "shim" in the middle of the parent layout, then align other elements to it. If you set the half-width element's width to match_parent, but align both their left and right sides, they'll end up shrinking themselves to fit.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.EqualWidthExample" >

    <!-- An invisible view aligned to the center of the parent. Allows other
    views to be arranged on either side -->
    <View 
        android:id="@+id/centerShim"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:visibility="invisible"
        android:layout_centerHorizontal="true"/>

    <!--Set width to match_parent sets maximum width. alignParentLeft aligns 
    the left edge of this view with the left edge of its parent. toLeftOf 
    sets the right edge of this view to align with the left edge of the 
    given view. The result of all three settings is that this view will 
    always take up exactly half of the width of its parent, however wide 
    that may be. -->
    <Button
        android:id="@+id/btLeft"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/centerShim"
        android:text="Left Button" />

    <!--Same deal, but on the right -->
    <Button
        android:id="@+id/btRight"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/centerShim"
        android:layout_below="@+id/tvLeft"
        android:text="Right Button" />
</RelativeLayout>