Android RelativeLayout align center of one view on top right corner of another view

FoamyGuy picture FoamyGuy · May 1, 2012 · Viewed 13.6k times · Source

I have experience with RelativeLayout but I've never run across a way to solve the problem I am presented with (aside from hard coding margin values, which I want to avoid.)

I want to try to create something like the following image in a RelativeLayout:

enter image description here

The box is its own View and I want to get the View that contains the orange circle to be centered on the top right corner of the View that contains the blue box.

I tried with android:alignTop="boxView" and android:alignRight="boxView" but that put my orange circle completely within my box. I want it to be so that the circle is centered above the top right corner of the box.

Anybody know how I can get that outcome with a RelativeLayout? preferably without having to hardcode margins away from the edge of the screen for the orange dot view.

Answer

Bobbake4 picture Bobbake4 · May 1, 2012

This code creates what you are looking for but does use margins. Now you can set the margin in code if this is a dynamic structure you are creating. As you can see I used negative margins to move the upper right shape outside of the blue box. These need to be half the height of the circle you are trying to move. You can do all of this in code to center the circle in the upper right corner.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:background="#0000FF"
            android:orientation="vertical" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="26dp"
            android:layout_height="26dp"
            android:layout_alignRight="@+id/linearLayout1"
            android:layout_alignTop="@+id/linearLayout1"
            android:layout_marginRight="-13dp"
            android:layout_marginTop="-13dp"
            android:background="#FF00FF"
            android:orientation="vertical" >
        </LinearLayout>

    </RelativeLayout>