Search code examples
androidandroid-relativelayout

Why is RelativeLayout not enforcing layout_alignLeft with layout_centerInParent view?


Why (the hell) isn't the RadioButton left edge correctly aligned with the gray square left edge?

Is this some kind of limitation or bug of RelativeLayout preventing from aligning a view to another view centered in parent ?

What would be the cleanest workaround?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_orange_dark">

    <View
        android:id="@+id/square"
        android:layout_width="200dip"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:background="@android:color/darker_gray"/>

    <RadioButton
        android:layout_alignLeft="@id/square"
        android:text="Radio button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_light"/>

    <View
        android:layout_width="300dp"
        android:layout_height="20dp"
        android:layout_centerInParent="true"
        android:background="@android:color/holo_green_light"
        />

</RelativeLayout>

screenshot from AS 2.2.3 Layout Editor. Android API: 25


Solution

  • You need to wrap your View and RadioButton in a RelativeLayout.

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@android:color/holo_orange_dark">
    
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">
    
        <View
            android:id="@+id/square"
            android:layout_width="200dip"
            android:layout_height="200dp"
            android:layout_centerInParent="true"
            android:background="@android:color/darker_gray"/>
    
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_light"
            android:text="Radio button"/>
    </RelativeLayout>
    
    <View
        android:layout_width="300dp"
        android:layout_height="20dp"
        android:layout_centerInParent="true"
        android:background="@android:color/holo_green_light"
        />